modified: src1/common.h
[GalaxyCodeBases.git] / c_cpp / pthreadtest / 02mutexex.c
blob36a6ed23bb49ad910064cb05ea400ab2e4130d22
1 /* mutexex.c */
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 */
7 #include <pthread.h>
8 #include <stdio.h>
10 void * simple(void *);
12 #define NUM_THREADS 2
13 pthread_t tid[NUM_THREADS]; /* array of thread IDs */
15 int bignum = 0;
16 pthread_mutex_t mut;
18 main( int argc, char *argv[] )
20 int i, ret;
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);
33 } /* main */
37 void * simple(void * parm)
39 int i;
40 for(i=0;i<10000;i++) {
41 pthread_mutex_lock(&mut);
42 bignum++; /* critical section */
43 pthread_mutex_unlock(&mut);