| 1 |
/* file: "tfib.c" */ |
| 2 |
|
| 3 |
#define USE_PTHREADS |
| 4 |
|
| 5 |
#ifdef USE_PTHREADS |
| 6 |
|
| 7 |
#include <stdio.h> |
| 8 |
#include <pthread.h> |
| 9 |
|
| 10 |
void *tfib (void *n) |
| 11 |
{ |
| 12 |
if ((int)n < 2) |
| 13 |
return (void*)1; |
| 14 |
else |
| 15 |
{ |
| 16 |
pthread_t x; |
| 17 |
void *y; |
| 18 |
void *z; |
| 19 |
if (pthread_create (&x, NULL, tfib, (void*)((int)n - 2)) != 0) exit (1); |
| 20 |
y = tfib ((void*)((int)n - 1)); |
| 21 |
if (pthread_join (x, &z) != 0) exit (1); |
| 22 |
return (void*)((int)y + (int)z); |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
int main (int argc, char *argv[]) |
| 27 |
{ |
| 28 |
int n = 14; /* atoi (argv[1]); */ |
| 29 |
int repeat = 100; /* atoi (argv[2]); */ |
| 30 |
void *result; |
| 31 |
do |
| 32 |
{ |
| 33 |
pthread_t x; |
| 34 |
if (pthread_create (&x, NULL, tfib, (void*)((int)n)) != 0) exit (1); |
| 35 |
if (pthread_join (x, &result) != 0) exit (1); |
| 36 |
repeat--; |
| 37 |
} while (repeat > 0); |
| 38 |
printf ("%d\n", (int)result); |
| 39 |
return 0; |
| 40 |
} |
| 41 |
|
| 42 |
#else |
| 43 |
|
| 44 |
#include <stdio.h> |
| 45 |
#include <sys/types.h> |
| 46 |
#include <sys/wait.h> |
| 47 |
#include <unistd.h> |
| 48 |
|
| 49 |
int tfib (int n) |
| 50 |
{ |
| 51 |
if (n < 2) |
| 52 |
return 1; |
| 53 |
else |
| 54 |
{ |
| 55 |
pid_t x; |
| 56 |
int y; |
| 57 |
int z; |
| 58 |
x = fork (); |
| 59 |
if (x < 0) exit (1); |
| 60 |
if (x == 0) exit (tfib (n - 2)); |
| 61 |
y = tfib (n - 1); |
| 62 |
if (waitpid (x, &z, 0) < 0) exit (1); |
| 63 |
return y + WEXITSTATUS(z); |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
int main (int argc, char *argv[]) |
| 68 |
{ |
| 69 |
int n = 14; /* atoi (argv[1]); */ |
| 70 |
int repeat = 20; /* atoi (argv[2]); */ |
| 71 |
int result; |
| 72 |
do |
| 73 |
{ |
| 74 |
pid_t x; |
| 75 |
x = fork (); |
| 76 |
if (x < 0) exit (1); |
| 77 |
if (x == 0) exit (tfib (n)); |
| 78 |
if (waitpid (x, &result, 0) < 0) exit (1); |
| 79 |
repeat--; |
| 80 |
} while (repeat > 0); |
| 81 |
printf ("fib(%d) mod 256 = %d\n", n, WEXITSTATUS(result)); |
| 82 |
return 0; |
| 83 |
} |
| 84 |
|
| 85 |
#endif |