| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <pthread.h> |
| 8 |
#include <stdio.h> |
| 9 |
|
| 10 |
/* Compute successive prime numbers (very inefficiently). Return the |
| 11 |
Nth prime number, where N is the value pointed to by *ARG. */ |
| 12 |
|
| 13 |
void* compute_prime (void* arg) |
| 14 |
{ |
| 15 |
int candidate = 2; |
| 16 |
int n = *((int*) arg); |
| 17 |
|
| 18 |
while (1) { |
| 19 |
int factor; |
| 20 |
int is_prime = 1; |
| 21 |
|
| 22 |
/* Test primality by successive division. */ |
| 23 |
for (factor = 2; factor < candidate; ++factor) |
| 24 |
if (candidate % factor == 0) { |
| 25 |
is_prime = 0; |
| 26 |
break; |
| 27 |
} |
| 28 |
/* Is this the prime number we're looking for? */ |
| 29 |
if (is_prime) { |
| 30 |
if (--n == 0) |
| 31 |
/* Return the desired prime number as the thread return value. */ |
| 32 |
return (void*) candidate; |
| 33 |
} |
| 34 |
++candidate; |
| 35 |
} |
| 36 |
return NULL; |
| 37 |
} |
| 38 |
|
| 39 |
int main () |
| 40 |
{ |
| 41 |
pthread_t thread; |
| 42 |
int which_prime = 5000; |
| 43 |
int prime; |
| 44 |
|
| 45 |
/* Start the computing thread, up to the 5000th prime number. */ |
| 46 |
pthread_create (&thread, NULL, &compute_prime, &which_prime); |
| 47 |
/* Do some other work here... */ |
| 48 |
/* Wait for the prime number thread to complete, and get the result. */ |
| 49 |
pthread_join (thread, (void*) &prime); |
| 50 |
/* Print the largest prime it computed. */ |
| 51 |
printf("The %dth prime number is %d.\n", which_prime, prime); |
| 52 |
return 0; |
| 53 |
} |