Hello all
I am currently coding a starter multi threading program in c. It is supposed to find all the prime numbers from 2 to n. I have no previous experience in thread coding so I am looking for some help and maybe some debugging advise It only calculates primes right for numbers less than 100. I need it to find a larger range but sadly I really don't know any c threading. Any and all help will be greatly appriciated. Here is my code:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/signal.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/errno.h>
#include <netinet/in.h>
#define INTERVAL 5 /* secs */
struct pthread
{
pthread_mutex_t mutex;
unsigned int prime;
int startValue;
int endValue;
} shared_global;
void CalculatePrimes();
int errexit(const char *format, ...);
int main(int argc, char *argv[])
{
pthread_t th;
pthread_attr_t ta;
int i;
shared_global.startValue = 2;
shared_global.prime = 0;
switch (argc)
{
case 1: shared_global.endValue = 0;
break;
case 2:shared_global.endValue = atoi(argv[1]);
break;
default:
printf("don't do that!\n");
exit(1);
}
(void) pthread_attr_init(&ta);
(void) pthread_attr_setdetachstate(&ta, PTHREAD_CREATE_DETACHED);
(void) pthread_mutex_init(&shared_global.mutex, 0);
for(i = 5;i < 9;i=i+1)
{
if (pthread_create(&th, &ta, (void * (*)(void *))CalculatePrimes,(void *) i) < 0)
{
printf("pthread_create failed\n");
exit(1);
}
printf("Thread created\n");
}
printf("There are %d primes.\n", shared_global.prime);
}
void CalculatePrimes()
{
bool isPrime;
while(shared_global.startValue < shared_global.endValue)
{
isPrime = true;
(void) pthread_mutex_lock(&shared_global.mutex);
for(int j=2; j<shared_global.startValue; j= j+1)
{
if (shared_global.startValue % j ==0)
{
isPrime = false;
}
}
if(isPrime)
{
printf("%d is a prime number.\n", shared_global.startValue);
shared_global.prime= shared_global.prime +1;
printf("this is a %d\n", shared_global.prime);
}
shared_global.startValue = shared_global.startValue +1;
(void) pthread_mutex_unlock(&shared_global.mutex);
}
//printf("There are %d prime numbers", shared_global.prime);
}
*The algorithm used to find the prime numbers is supposed to be inefficent because it is used as a bench mark. Thank you.