3 * gcc pthread_mutex.c -o pthread_mutex -lpthread -Wall -W -Wextra -ansi -pedantic
13 int myglobal
= 0; /* global shared variable */
14 pthread_mutex_t mymutex
= PTHREAD_MUTEX_INITIALIZER
;
16 /* Function prototypes */
17 void *threadfun(void *arg
);
18 void diep(const char *s
);
22 pthread_t tid
[NUM_THREADS
];
25 /* Create the threads */
26 for (i
= 0; i
< NUM_THREADS
; i
++) {
27 if (pthread_create(&tid
[i
], NULL
, threadfun
, NULL
))
28 diep("pthread_create");
31 /* Make sure all threads are done */
32 for (i
= 0; i
< NUM_THREADS
; i
++) {
33 if (pthread_join(tid
[i
], NULL
))
37 printf("myglobal = %d\n", myglobal
);
42 void *threadfun(void *arg
)
46 for (i
= 0; i
< 5; i
++) {
47 pthread_mutex_lock(&mymutex
); /* Begin of critical region */
52 pthread_mutex_unlock(&mymutex
); /* End of critical region */
57 void diep(const char *s
)