3 * gcc pthread_semaphore.c -o pthread_semaphore -lpthread -Wall -W -Wextra -ansi -pedantic
15 int myglobal
= 0; /* global shared variable */
17 /* Function prototypes */
18 void *threadfun(void *arg
);
19 void diep(const char *s
);
23 pthread_t tid
[NUM_THREADS
];
26 /* Initialize the semaphore */
27 if (sem_init(&mutex
, 0, 1))
30 /* Create the threads */
31 for (i
= 0; i
< NUM_THREADS
; i
++)
32 if (pthread_create(&tid
[i
], NULL
, threadfun
, NULL
))
33 diep("pthread_create");
35 /* Make sure all threads are done */
36 for (i
= 0; i
< NUM_THREADS
; i
++)
37 if (pthread_join(tid
[i
], NULL
))
40 printf("myglobal = %d\n", myglobal
);
45 void *threadfun(void *arg
)
49 for (i
= 0; i
< 5; i
++) {
50 sem_wait(&mutex
); /* begin critical region */
55 sem_post(&mutex
); /* end critical region */
61 void diep(const char *s
)