sewardj | d985979 | 2002-04-12 21:57:01 +0000 | [diff] [blame] | 1 | /******************************************************** |
| 2 | * An example source module to accompany... |
| 3 | * |
| 4 | * "Using POSIX Threads: Programming with Pthreads" |
| 5 | * by Brad nichols, Dick Buttlar, Jackie Farrell |
| 6 | * O'Reilly & Associates, Inc. |
| 7 | * |
| 8 | ******************************************************** |
| 9 | * simple_mutex.c |
| 10 | * |
| 11 | * Simple multi-threaded example with a mutex lock. |
| 12 | */ |
| 13 | #include <stdlib.h> |
| 14 | #include <stdio.h> |
| 15 | #include <errno.h> |
| 16 | #include <pthread.h> |
| 17 | |
| 18 | void do_one_thing(int *); |
| 19 | void do_another_thing(int *); |
| 20 | void do_wrap_up(int, int); |
| 21 | |
| 22 | int r1 = 0, r2 = 0, r3 = 0; |
| 23 | pthread_mutex_t r3_mutex=PTHREAD_MUTEX_INITIALIZER; |
| 24 | |
| 25 | extern int |
| 26 | main(int argc, char **argv) |
| 27 | { |
| 28 | pthread_t thread1, thread2; |
| 29 | |
| 30 | if (argc > 1) |
| 31 | r3 = atoi(argv[1]); |
| 32 | |
| 33 | if (pthread_create(&thread1, |
| 34 | NULL, |
| 35 | (void *) do_one_thing, |
| 36 | (void *) &r1) != 0) |
| 37 | perror("pthread_create"),exit(1); |
| 38 | |
| 39 | if (pthread_create(&thread2, |
| 40 | NULL, |
| 41 | (void *) do_another_thing, |
| 42 | (void *) &r2) != 0) |
| 43 | perror("pthread_create"),exit(1); |
| 44 | |
| 45 | if (pthread_join(thread1, NULL) != 0) |
| 46 | perror("pthread_join"), exit(1); |
| 47 | |
| 48 | if (pthread_join(thread2, NULL) != 0) |
| 49 | perror("pthread_join"), exit(1); |
| 50 | |
| 51 | do_wrap_up(r1, r2); |
| 52 | |
| 53 | return 0; |
| 54 | } |
| 55 | |
| 56 | void do_one_thing(int *pnum_times) |
| 57 | { |
| 58 | int i, j, x; |
| 59 | |
| 60 | pthread_mutex_lock(&r3_mutex); |
| 61 | if(r3 > 0) { |
| 62 | x = r3; |
| 63 | r3--; |
| 64 | } else { |
| 65 | x = 1; |
| 66 | } |
| 67 | pthread_mutex_unlock(&r3_mutex); |
| 68 | |
| 69 | for (i = 0; i < 4; i++) { |
| 70 | printf("doing one thing\n"); |
| 71 | for (j = 0; j < 100000; j++) x = x + i; |
| 72 | (*pnum_times)++; |
| 73 | } |
| 74 | |
| 75 | } |
| 76 | |
| 77 | void do_another_thing(int *pnum_times) |
| 78 | { |
| 79 | int i, j, x; |
| 80 | |
| 81 | pthread_mutex_lock(&r3_mutex); |
| 82 | if(r3 > 0) { |
| 83 | x = r3; |
| 84 | r3--; |
| 85 | } else { |
| 86 | x = 1; |
| 87 | } |
| 88 | pthread_mutex_unlock(&r3_mutex); |
| 89 | |
| 90 | for (i = 0; i < 4; i++) { |
| 91 | printf("doing another \n"); |
| 92 | for (j = 0; j < 100000; j++) x = x + i; |
| 93 | (*pnum_times)++; |
| 94 | } |
| 95 | |
| 96 | } |
| 97 | |
| 98 | void do_wrap_up(int one_times, int another_times) |
| 99 | { |
| 100 | int total; |
| 101 | |
| 102 | total = one_times + another_times; |
| 103 | printf("All done, one thing %d, another %d for a total of %d\n", |
| 104 | one_times, another_times, total); |
| 105 | } |