10 int myglobal
= 0; /* global shared variable */
12 /* function prototypes */
13 void *threadfun(void *arg
);
16 pthread_t tid
[NUM_THREADS
];
19 /* initialize the semaphore */
20 if (sem_init(&mutex
, 0, 1)) {
21 fprintf(stderr
, "sem_init() error\n");
25 /* create the threads */
26 for (i
=0; i
<NUM_THREADS
; i
++) {
27 if (pthread_create(&tid
[i
], NULL
, threadfun
, NULL
)) {
28 fprintf(stderr
, "pthread_create() error\n");
33 /* make sure all threads are done */
34 for (i
=0; i
<NUM_THREADS
; i
++)
35 if (pthread_join(tid
[i
], NULL
)) {
36 fprintf(stderr
, "pthread_join() error\n");
40 printf("myglobal = %d\n", myglobal
);
45 void *threadfun(void *arg
) {
49 sem_wait(&mutex
); /* begin critical region */
54 sem_post(&mutex
); /* end critical region */