Please assist I want to create 5 threads to compute the prim
Please assist, I want to create 5 threads to compute the prime number. I have tried this way using this code below, but I have been told it\'s not correct.
Solution
//compile with -pthread flag
//function pthread_join is given incorrect cast in argument it\'s void** required
#include <pthread.h> //Header for using pthread
#include <stdio.h>
#define NUM_THREADS 5
pthread_mutex_t mutexprime;
int n; //nth prime is required
int candidate = 2; //starting candidate
int destroy = 0; //for destroying other threads once answer is obtained
int answer ; //storing answer // Above are global variables shared among threads
void* compute_prime (void* arg)
{
while (1) {
pthread_mutex_lock (&mutexprime);
int factor;
int is_prime = 1;
/* Test primality by successive division. */
for (factor = 2; factor*factor <= candidate; ++factor)
if (candidate % factor == 0) {
is_prime = 0;
break;
}
if(destroy){ pthread_mutex_unlock (&mutexprime); return (void*)answer;} //returning from thread after unlocking mutex lock
/* Is this the prime number we\'re looking for? */
if (is_prime)
{
if (--n == 0){ //n =0 implies the prime number we require is obtained
/* Return the desired prime number as the thread return value. */
//
pthread_mutex_unlock (&mutexprime);
destroy =1; //make destroy =1 to make other threads return
answer = candidate;
return (void*) answer;
}
printf(\"%d is a prime number and n is %d \ \",candidate,n);
//
}
++candidate; //increment candidate to be tested for primality
pthread_mutex_unlock (&mutexprime);
}
return NULL;
}
int main ()
{
// pthread_t thread;
int which_prime = 5000; //nth prime to be found
int prime;
n = which_prime;
pthread_t thread[NUM_THREADS];
pthread_attr_t attr;
int rc;
long t;
void *status;
/* Create a mutex guard*/
pthread_mutex_init(&mutexprime, NULL);
/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(t=0; t<NUM_THREADS; t++) {
// rc = pthread_create(&thread[t], &compute_prime, &which_prime);
rc= pthread_create (&thread[t], NULL, &compute_prime, &which_prime); //creating threads
}
/* Free attribute and wait for the other threads */
pthread_attr_destroy(&attr);
for(t=0; t<NUM_THREADS; t++) {
rc = pthread_join(thread[t],(void**)&prime); //joining threads so that main function doesn\'t exit
}
/* Start the computing thread, up to the 5000th prime number. */
//pthread_create (&thread, NULL, &compute_prime, &which_prime);
/* Do some other work here... */
/* Wait for the prime number thread to complete, and get the result. */
//pthread_join (thread, (void*) &prime);
/* Print the largest prime it computed. */
printf(\"The %dth prime number is %d.\ \", which_prime, prime);
pthread_mutex_destroy(&mutexprime);
return 0;
}

