Rename semaphore.c to pthread_semaphore.c
[eleutheria.git] / pthread_semaphore.c
bloba8beb2d96888b736a5a0bbe6a67fd673d7470721
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <pthread.h>
4 #include <semaphore.h>
5 #include <unistd.h>
7 #define NUM_THREADS 5
9 sem_t mutex;
10 int myglobal = 0; /* global shared variable */
12 /* function prototypes */
13 void *threadfun(void *arg);
15 int main(void) {
16 pthread_t tid[NUM_THREADS];
17 int i;
19 /* initialize the semaphore */
20 if (sem_init(&mutex, 0, 1)) {
21 fprintf(stderr, "sem_init() error\n");
22 exit(EXIT_FAILURE);
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");
29 exit(EXIT_FAILURE);
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");
37 exit(EXIT_FAILURE);
40 printf("myglobal = %d\n", myglobal);
42 return EXIT_SUCCESS;
45 void *threadfun(void *arg) {
46 int i, j;
48 for (i=0; i<5; i++) {
49 sem_wait(&mutex); /* begin critical region */
50 j = myglobal;
51 j++;
52 sleep(1);
53 myglobal = j;
54 sem_post(&mutex); /* end critical region */
57 pthread_exit(NULL);