Cosmetic changes
[eleutheria.git] / pthreads / pthread_mutex.c
bloba53e30e3185f02500c921280499b912beec3702d
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <pthread.h>
4 #include <unistd.h>
6 #define NUM_THREADS 5
8 int myglobal = 0; /* global shared variable */
9 pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
11 /* function prototypes */
12 void *threadfun(void *arg);
14 int main() {
15 pthread_t tid[NUM_THREADS];
16 int i;
18 /* create the threads */
19 for (i=0; i<NUM_THREADS; i++) {
20 if (pthread_create(&tid[i], NULL, threadfun, NULL)) {
21 fprintf(stderr, "pthread_create() error\n");
22 exit(EXIT_FAILURE);
26 /* make sure all threads are done */
27 for (i=0; i<NUM_THREADS; i++) {
28 if (pthread_join(tid[i], NULL)) {
29 fprintf(stderr, "pthread_join() error\n");
30 exit(EXIT_FAILURE);
34 printf("myglobal = %d\n", myglobal);
36 return EXIT_SUCCESS;
39 void *threadfun(void *arg) {
40 int i, j;
42 for (i=0; i<5; i++) {
43 pthread_mutex_lock(&mymutex); /* Begin of critical region */
44 j = myglobal;
45 j++;
46 sleep(1); /* */
47 myglobal = j;
48 pthread_mutex_unlock(&mymutex); /* End of critical region */
50 pthread_exit(NULL);