2 gcc pthread_mutex.c -o pthread_mutex -lpthread -Wall -W -Wextra -ansi -pedantic */
11 int myglobal
= 0; /* global shared variable */
12 pthread_mutex_t mymutex
= PTHREAD_MUTEX_INITIALIZER
;
14 /* function prototypes */
15 void *threadfun(void *arg
);
18 pthread_t tid
[NUM_THREADS
];
21 /* create the threads */
22 for (i
=0; i
<NUM_THREADS
; i
++) {
23 if (pthread_create(&tid
[i
], NULL
, threadfun
, NULL
)) {
24 fprintf(stderr
, "pthread_create() error\n");
29 /* make sure all threads are done */
30 for (i
=0; i
<NUM_THREADS
; i
++) {
31 if (pthread_join(tid
[i
], NULL
)) {
32 fprintf(stderr
, "pthread_join() error\n");
37 printf("myglobal = %d\n", myglobal
);
42 void *threadfun(void *arg
) {
46 pthread_mutex_lock(&mymutex
); /* Begin of critical region */
51 pthread_mutex_unlock(&mymutex
); /* End of critical region */