8 int myglobal
= 0; /* global shared variable */
9 pthread_mutex_t mymutex
= PTHREAD_MUTEX_INITIALIZER
;
11 /* function prototypes */
12 void *threadfun(void *arg
);
15 pthread_t tid
[NUM_THREADS
];
18 /* create the threads */
19 for (i
=0; i
<NUM_THREADS
; i
++) {
20 if (pthread_create(&tid
[i
], NULL
, threadfun
, NULL
)) {
21 fprintf(stderr
, "pthread_create() error\n");
26 /* make sure all threads are done */
27 for (i
=0; i
<NUM_THREADS
; i
++) {
28 if (pthread_join(tid
[i
], NULL
)) {
29 fprintf(stderr
, "pthread_join() error\n");
34 printf("myglobal = %d\n", myglobal
);
39 void *threadfun(void *arg
) {
43 pthread_mutex_lock(&mymutex
); /* Begin of critical region */
48 pthread_mutex_unlock(&mymutex
); /* End of critical region */