2 gcc pthread_semaphore.c -o pthread_semaphore -lpthread -Wall -W -Wextra -ansi -pedantic */
13 int myglobal
= 0; /* global shared variable */
15 /* function prototypes */
16 void *threadfun(void *arg
);
17 void diep(const char *s
);
21 pthread_t tid
[NUM_THREADS
];
24 /* initialize the semaphore */
25 if (sem_init(&mutex
, 0, 1))
28 /* create the threads */
29 for (i
= 0; i
< NUM_THREADS
; i
++)
30 if (pthread_create(&tid
[i
], NULL
, threadfun
, NULL
))
31 diep("pthread_create");
33 /* make sure all threads are done */
34 for (i
= 0; i
< NUM_THREADS
; i
++)
35 if (pthread_join(tid
[i
], NULL
))
38 printf("myglobal = %d\n", myglobal
);
43 void *threadfun(void *arg
)
48 sem_wait(&mutex
); /* begin critical region */
53 sem_post(&mutex
); /* end critical region */
59 void diep(const char *s
)