Skip to content

Instantly share code, notes, and snippets.

/gist:5130987

Created Mar 10, 2013
Embed
What would you like to do?
#include <stdio.h>
#include <pthread.h>
struct range
{
unsigned long long start;
unsigned long long end;
} range;
void *sumprimes(void *r);
int isprime(unsigned long int);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
unsigned long long globaltotal = 2;
int main(int argc, char *argv)
{
int rc1, rc2, rc3, rc4;
pthread_t thread1, thread2, thread3, thread4;
struct range range1, range2, range3, range4;
range1.start = 3; range1.end = 500000;
range2.start = 500001; range2.end = 1000000;
range3.start = 1000001; range3.end = 1500000;
range4.start = 1500001; range4.end = 2000000;
rc1 = pthread_create(&thread1, NULL, &sumprimes, (void *)&range1);
rc2 = pthread_create(&thread2, NULL, &sumprimes, (void *)&range2);
rc3 = pthread_create(&thread3, NULL, &sumprimes, (void *)&range3);
rc4 = pthread_create(&thread4, NULL, &sumprimes, (void *)&range4);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
pthread_join(thread4, NULL);
printf("Total is: %llu\n", globaltotal);
return 0;
}
void *sumprimes(void *r)
{
struct range *x = (struct range *)r;
unsigned long long start = x->start;
unsigned long long end = x->end;
unsigned long long n, total = 0;
printf("Adding primes from %llu to %llu\n", start, end);
for (n = start; n <= end; n+=2)
{
if (isprime(n))
{
total = total + n;
}
}
pthread_mutex_lock(&mutex1);
globaltotal = globaltotal + total;
pthread_mutex_unlock(&mutex1);
printf("Done adding primes from %llu to %llu\n", start, end);
}
int isprime(unsigned long int x)
{
unsigned long int index;
if(x % 2 == 0) {return 0;}
for (index = 3; index < x; index++)
{
if ((x % index) == 0)
{
return 0;
}
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.