Add comment clarifying prop_array_t data type
[eleutheria.git] / pthreads / pthread_semaphore.c
blobb4f7f1ea14c290a8b0b31cafc0448e0afdb8dff4
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);