Merge branch 'exp-hash'
[eleutheria.git] / pthreads / pthread_semaphore.c
blobd7bf8fa495ad54d45aed2dedb778fe5ef55d1919
1 /* compile with:
2 gcc pthread_semaphore.c -o pthread_semaphore -lpthread -Wall -W -Wextra -ansi -pedantic */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <pthread.h>
7 #include <semaphore.h>
8 #include <unistd.h>
10 #define NUM_THREADS 5
12 sem_t mutex;
13 int myglobal = 0; /* global shared variable */
15 /* function prototypes */
16 void *threadfun(void *arg);
17 void diep(const char *s);
19 int main(void)
21 pthread_t tid[NUM_THREADS];
22 int i;
24 /* initialize the semaphore */
25 if (sem_init(&mutex, 0, 1))
26 diep("sem_init");
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))
36 diep("pthread_join");
38 printf("myglobal = %d\n", myglobal);
40 return EXIT_SUCCESS;
43 void *threadfun(void *arg)
45 int i, j;
47 for (i=0; i<5; i++) {
48 sem_wait(&mutex); /* begin critical region */
49 j = myglobal;
50 j++;
51 sleep(1);
52 myglobal = j;
53 sem_post(&mutex); /* end critical region */
56 pthread_exit(NULL);
59 void diep(const char *s)
61 perror(s);
62 exit(EXIT_FAILURE);