#include #include #include #include #include #include #define MAXX 100000 #define NTHREADS 30 #ifndef NULL #define NULL (void *)0 #endif typedef struct { char header[20]; int count; int data[MAXX]; } accumul; typedef struct { int threadNum; } threadInfo; accumul primes; _Atomic long num = ATOMIC_VAR_INIT(19); pthread_mutex_t mutexUP; void updatePrimes(long newP) { pthread_mutex_lock(&mutexUP); primes.data[primes.count++] = newP; pthread_mutex_unlock(&mutexUP); } void* getPrimes(void * args) { threadInfo *tInfo = args; while (primes.count < MAXX - 1) { long np = atomic_fetch_add(&num, 2); long sq = sqrt(np); int g = 1; int mxx = primes.count - 2; for (long i = 0; g == 1 && i < mxx && primes.data[i] <= np; i++) { if (np % primes.data[i] == 0) g = 0; } if (g) { updatePrimes(np); if (primes.count % 1000 == 0) printf("%d %d %ld\n", tInfo->threadNum, primes.count, primes.data[primes.count - 1]); } } } int main(int argc, char const *argv[]) { primes.data[0] = 3; primes.data[1] = 5; primes.data[2] = 7; primes.data[3] = 11; primes.data[4] = 13; primes.data[5] = 17; primes.data[6] = 19; pthread_mutex_init(&mutexUP, NULL); pthread_t threads[NTHREADS]; threadInfo tInfo[NTHREADS]; for (int i = 0; i < NTHREADS; i++) { tInfo[i] = (threadInfo){.threadNum = i}; pthread_create(threads + i, NULL, getPrimes, &tInfo[i]); if (i==0) sleep(1); // give the first thread a little time to get the small primes } for (int i = 0; i < NTHREADS; i++) { pthread_join(threads[i], NULL); printf("Joined %d\n", i); } for (int i = (primes.count-10); i < primes.count; i++) { printf("%4d %9d\n", i, primes.data[i]); } return 0; }