Dummy commit to test new ssh key
[eleutheria.git] / pthreads / pthread_mutex.c
blobdb5a0168500c155b72aa14dddafd6efedb392d82
1 /*
2 * Compile with:
3 * gcc pthread_mutex.c -o pthread_mutex -lpthread -Wall -W -Wextra -ansi -pedantic
4 */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <pthread.h>
9 #include <unistd.h>
11 #define NUM_THREADS 5
13 int myglobal = 0; /* global shared variable */
14 pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
16 /* Function prototypes */
17 void *threadfun(void *arg);
18 void diep(const char *s);
20 int main(void)
22 pthread_t tid[NUM_THREADS];
23 int i;
25 /* Create the threads */
26 for (i = 0; i < NUM_THREADS; i++) {
27 if (pthread_create(&tid[i], NULL, threadfun, NULL))
28 diep("pthread_create");
31 /* Make sure all threads are done */
32 for (i = 0; i < NUM_THREADS; i++) {
33 if (pthread_join(tid[i], NULL))
34 diep("pthread_join");
37 printf("myglobal = %d\n", myglobal);
39 return EXIT_SUCCESS;
42 void *threadfun(void *arg)
44 int i, j;
46 for (i = 0; i < 5; i++) {
47 pthread_mutex_lock(&mymutex); /* Begin of critical region */
48 j = myglobal;
49 j++;
50 sleep(1);
51 myglobal = j;
52 pthread_mutex_unlock(&mymutex); /* End of critical region */
54 pthread_exit(NULL);
57 void diep(const char *s)
59 perror(s);
60 exit(EXIT_FAILURE);