I'm trying to implement threads with Project Euler problem 10. I am getting different results for the sum of the primes every time I run the program. I realize the code is quite atrocious; this is my first experiment with threads. In addition, if anyone could suggest a better way to distribute the load, I would appreciate it.
Code:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define NUM 2000000
#define NUM_THREADS 4
int isPrime(long int x)
{
long int y;
int z = 0;
for(y = 1; y <= x; y++)
{
if(x % y == 0)
z++;
}
if(z == 2)
return 1;
else
return 0;
}
void *first(void *sum)
{
long int x;
long int *y;
y = (long int*)sum;
for(x = 2; x < (NUM * 1/4); x++)
{
if(isPrime(x))
*y += x;
}
printf("Sum of primes in first(), %ld\n", *y);
pthread_exit(NULL);
}
void *second(void *sum)
{
long int x;
long int *y;
y = (long int*)sum;
for(x = (NUM * 1/4); x < (NUM * 1/2); x++)
{
if(isPrime(x))
*y += x;
}
pthread_exit(NULL);
}
void *third(void *sum)
{
long int x;
long int *y;
y = (long int*)sum;
for(x = (NUM * 1/2); x < (NUM * 3/4); x++)
{
if(isPrime(x))
*y += x;
}
pthread_exit(NULL);
}
void *fourth(void *sum)
{
long int x;
long int *y;
y = (long int*)sum;
for(x = (NUM * 3/4); x < NUM; x++)
{
if(isPrime(x))
*y += x;
}
pthread_exit(NULL);
}
int main(void)
{
void *sum = malloc(sizeof(long int));
pthread_t threads[NUM_THREADS];
int rc;
long int *z;
rc = pthread_create(&threads[0], NULL, first, (void *)sum);
if(rc)
printf("ERROR; return code from pthread_create() is %i\n", rc);
else{rc = 0; printf("Thread %ld created.\n", &threads[0]);}
rc = pthread_create(&threads[1], NULL, second, (void *)sum);
if(rc)
printf("ERROR; return code from pthread_create() is %i\n", rc);
else{rc = 0; printf("Thread %ld created.\n", &threads[1]);}
rc = pthread_create(&threads[2], NULL, third, (void *)sum);
if(rc)
printf("ERROR; return code from pthread_create() is %i\n", rc);
else{rc = 0; printf("Thread %ld created.\n", &threads[2]);}
rc = pthread_create(&threads[3], NULL, fourth, (void *)sum);
if(rc)
printf("ERROR; return code from pthread_create() is %i\n", rc);
else{rc = 0; printf("Thread %ld created.\n", &threads[3]);}
z = (long int*)sum;
printf("=======================\n");
printf("%ld\n", *z);
printf("=======================\n");
return 0;
}