ch4-primes

Chapter_4     create2 detach







primes.c     ALP, p. 67-68


#include <stdio.h> // for printf()
#include <pthread.h> // for pthread_t, pthread_create(), pthread_join()

unsigned long primes[5000];
unsigned idx = 0; // index of primes[]

/* Compute successive prime numbers. Return the
nth prime number, where `n' is the value pointed to by *arg. */
void * compute_prime (void * arg);

int main()
{
pthread_t thread;
unsigned which_prime = 5000;
unsigned long *prime;
primes[idx++] = 2; // primes[0] = 2;
/* Start the computing thread, up to the 5,000th prime number. */
pthread_create (&thread, NULL, &compute_prime, &which_prime);
/* Wait for prime number thread to complete, and get the result. */
pthread_join (thread, (void**) &prime);
/* Print the largest prime it computed. */
printf("The %uth prime number is %lu.\n", which_prime, *prime);
printf("The %uth prime number is %lu.\n", which_prime, primes[idx-1]);

return 0;
}
/* Compute successive prime numbers. Return the
nth prime number, where `n' is the value pointed to by *arg. */
void * compute_prime (void * arg)
{
unsigned n = *((unsigned*) arg);
if (n <= idx) // first prime is primes[0]
{return (void*) (primes+n-1);} // &primes[n-1]
// else
unsigned long candidate = primes[idx-1]+1; // last recorded prime + 1
unsigned long half;
unsigned i, is_prime;

while (1)
{
is_prime = 1; // (re)set
half = candidate / 2;

for (i = 0; primes[i] <= half; i++)
{ /* Test primality by successive division (modulo): */
if (candidate % primes[i] == 0)
{
is_prime = 0; // not prime
break; // out of for(), test next candidate
}
}

if (is_prime)
{ /* Is this the prime number we're looking for? */
primes[idx++] = candidate;
// printf("primes[%u] = %lu\n", idx-1, candidate);
if (n <= idx)
{ // Return the desired prime number as the
return (void*) (primes+idx-1); // thread return value
} // &primes[idx-1], &candidate
}
// else
++candidate; // the next candidate
}

return NULL;
}
/*
gcc primes.c -o primes -lpthread
./primes
The 5000th prime number is 48611.
The 5000th prime number is 48611.
https://prime-numbers.info/number/5000th-prime
*/





Notes:

See 5000th-prime on Prime_Numbers.
In main(), prime must be a pointer such that &prime can be converted to void**, argument of pthread_join().
We cannot return &candidate from compute_prime() because candidate is a local variable. However, we can say,
int *p = &candidate;
return (void*)p;









Chapter_4     create2 BACK_TO_TOP detach



Comments

Popular posts from this blog

Contents