Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Replace memset(..., 0, ...) with zero-initialization.
[simgrid.git] / examples / sthread / pthread-mutex-simpledeadlock.c
1 /* Simple test code that may deadlock:
2
3    Thread 1 locks mutex1 then mutex2 while thread 2 locks in reverse order.
4    Deadlock occurs when each thread get one mutex and then ask for the other one.
5  */
6
7 #include <pthread.h>
8 #include <stdio.h>
9
10 pthread_mutex_t mutex1;
11 pthread_mutex_t mutex2;
12
13 static void* thread_fun1(void* val)
14 {
15   pthread_mutex_lock(&mutex1);
16   pthread_mutex_lock(&mutex2);
17   pthread_mutex_unlock(&mutex1);
18   pthread_mutex_unlock(&mutex2);
19
20   fprintf(stderr, "The thread %d is terminating.\n", *(int*)val);
21   return NULL;
22 }
23 static void* thread_fun2(void* val)
24 {
25   pthread_mutex_lock(&mutex2);
26   pthread_mutex_lock(&mutex1);
27   pthread_mutex_unlock(&mutex1);
28   pthread_mutex_unlock(&mutex2);
29
30   fprintf(stderr, "The thread %d is terminating.\n", *(int*)val);
31   return NULL;
32 }
33
34 int main(int argc, char* argv[])
35 {
36   pthread_mutex_init(&mutex1, NULL);
37   pthread_mutex_init(&mutex2, NULL);
38
39   int id[2] = {0, 1};
40   pthread_t thread1;
41   pthread_t thread2;
42   pthread_create(&thread1, NULL, thread_fun1, &id[0]);
43   pthread_create(&thread2, NULL, thread_fun2, &id[1]);
44   fprintf(stderr, "All threads are started.\n");
45   pthread_join(thread1, NULL);
46   pthread_join(thread2, NULL);
47
48   pthread_mutex_destroy(&mutex1);
49   pthread_mutex_destroy(&mutex2);
50
51   fprintf(stderr, "User's main is terminating.\n");
52   return 0;
53 }