1 /* Simple test code that may deadlock:
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.
10 pthread_mutex_t mutex1;
11 pthread_mutex_t mutex2;
13 static void* thread_fun1(void* val)
15 pthread_mutex_lock(&mutex1);
16 pthread_mutex_lock(&mutex2);
17 pthread_mutex_unlock(&mutex1);
18 pthread_mutex_unlock(&mutex2);
20 fprintf(stderr, "The thread %d is terminating.\n", *(int*)val);
23 static void* thread_fun2(void* val)
25 pthread_mutex_lock(&mutex2);
26 pthread_mutex_lock(&mutex1);
27 pthread_mutex_unlock(&mutex1);
28 pthread_mutex_unlock(&mutex2);
30 fprintf(stderr, "The thread %d is terminating.\n", *(int*)val);
34 int main(int argc, char* argv[])
36 pthread_mutex_init(&mutex1, NULL);
37 pthread_mutex_init(&mutex2, NULL);
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);
48 pthread_mutex_destroy(&mutex1);
49 pthread_mutex_destroy(&mutex2);
51 fprintf(stderr, "User's main is terminating.\n");