Define matrix data type and use it instead of struct matrix
[eleutheria.git] / pthreads / pthread_mutex.c
blob4c8b8f557dd682230e9cc56671765db92064420d
1 /* compile with:
2 gcc pthread_mutex.c -o pthread_mutex -lpthread -Wall -W -Wextra -ansi -pedantic */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <pthread.h>
7 #include <unistd.h>
9 #define NUM_THREADS 5
11 int myglobal = 0; /* global shared variable */
12 pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
14 /* function prototypes */
15 void *threadfun(void *arg);
17 int main() {
18 pthread_t tid[NUM_THREADS];
19 int i;
21 /* create the threads */
22 for (i=0; i<NUM_THREADS; i++) {
23 if (pthread_create(&tid[i], NULL, threadfun, NULL)) {
24 fprintf(stderr, "pthread_create() error\n");
25 exit(EXIT_FAILURE);
29 /* make sure all threads are done */
30 for (i=0; i<NUM_THREADS; i++) {
31 if (pthread_join(tid[i], NULL)) {
32 fprintf(stderr, "pthread_join() error\n");
33 exit(EXIT_FAILURE);
37 printf("myglobal = %d\n", myglobal);
39 return EXIT_SUCCESS;
42 void *threadfun(void *arg) {
43 int i, j;
45 for (i=0; i<5; i++) {
46 pthread_mutex_lock(&mymutex); /* Begin of critical region */
47 j = myglobal;
48 j++;
49 sleep(1); /* */
50 myglobal = j;
51 pthread_mutex_unlock(&mymutex); /* End of critical region */
53 pthread_exit(NULL);