pthreads changed
[eleutheria.git] / pthreads / pthread_semaphore.c
blob320e98b266285ddc7a1b42242519582109a6f15d
1 /*
2 * Compile with:
3 * gcc pthread_semaphore.c -o pthread_semaphore -lpthread -Wall -W -Wextra -ansi -pedantic
4 */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <pthread.h>
9 #include <semaphore.h>
10 #include <unistd.h>
12 #define NUM_THREADS 5
14 sem_t mutex;
15 int myglobal = 0; /* global shared variable */
17 /* Function prototypes */
18 void *threadfun(void *arg);
19 void diep(const char *s);
21 int main(void)
23 pthread_t tid[NUM_THREADS];
24 int i;
26 /* Initialize the semaphore */
27 if (sem_init(&mutex, 0, 1))
28 diep("sem_init");
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))
38 diep("pthread_join");
40 printf("myglobal = %d\n", myglobal);
42 return EXIT_SUCCESS;
45 void *threadfun(void *arg)
47 int i, j;
49 for (i = 0; i < 5; i++) {
50 sem_wait(&mutex); /* begin critical region */
51 j = myglobal;
52 j++;
53 sleep(1);
54 myglobal = j;
55 sem_post(&mutex); /* end critical region */
58 pthread_exit(NULL);
61 void diep(const char *s)
63 perror(s);
64 exit(EXIT_FAILURE);