2 /* Simple pthread example using pthread_mutex to ensure mutual exclusion */
3 /* This corrects the bug from raceexample.c */
4 /* To compile me for Linux, type: gcc -o filename filename.c -lpthread */
5 /* To execute, type: filename */
10 void * simple(void *);
13 pthread_t tid
[NUM_THREADS
]; /* array of thread IDs */
18 main( int argc
, char *argv
[] )
22 pthread_mutex_init(&mut
, NULL
);
24 for (i
=0; i
<NUM_THREADS
; i
++) {
25 pthread_create(&tid
[i
], NULL
, simple
, NULL
);
27 for ( i
= 0; i
< NUM_THREADS
; i
++)
28 pthread_join(tid
[i
], NULL
);
30 printf("main() reporting that all %d threads have terminated\n", i
);
31 printf("I am main! bignum=%d\n", bignum
);
37 void * simple(void * parm
)
40 for(i
=0;i
<10000;i
++) {
41 pthread_mutex_lock(&mut
);
42 bignum
++; /* critical section */
43 pthread_mutex_unlock(&mut
);