#include #include #include pthread_mutex_t current_mutex; size_t current = 3; size_t done = 100000; int n_threads = 4; char is_prime(size_t cand){ for(size_t i = 3; i < (cand+1)/2; i += 2) if(! (cand % i)) return 0; return 1; } void *worker(void* param){ do { // Take assignment pthread_mutex_lock(¤t_mutex); size_t ours = current + 2; current += 2; pthread_mutex_unlock(¤t_mutex); // Check. This takes a while, so we should be unlocked if(is_prime(ours)) printf("Found Prime: %lu\n", ours); } while(current < done); return 0; } int main(int argc, char ** argv){ if(argc > 2){ n_threads = atoi(argv[1]); done = atoll(argv[2]); } pthread_t threads[48]; pthread_mutex_init(¤t_mutex, 0); for(int i = 0; i < n_threads; i++) pthread_create(threads + i, 0, worker, 0); for(int i = 0; i < n_threads; i++) pthread_join(threads[i], 0); return 0; }