blob: e5b5854faff343212b5a13c99fdd6490868e5552 [file] [log] [blame]
bart8bba1f72008-02-27 16:13:05 +00001/** Initialize several kinds of mutexes and lock each mutex twice.
2 * Note: locking a regular mutex twice causes a deadlock.
bart5357fcb2008-02-27 15:46:00 +00003 */
4
5#define _GNU_SOURCE
6
7#include <stdio.h>
bart4240ff32008-02-27 17:41:22 +00008#include <unistd.h>
bart5357fcb2008-02-27 15:46:00 +00009#include <pthread.h>
10
bart4240ff32008-02-27 17:41:22 +000011
bart5357fcb2008-02-27 15:46:00 +000012static void lock_twice(pthread_mutex_t* const p)
13{
14 pthread_mutex_lock(p);
15 pthread_mutex_lock(p);
16 pthread_mutex_unlock(p);
17 pthread_mutex_unlock(p);
18}
19
20int main(int argc, char** argv)
21{
bart8bba1f72008-02-27 16:13:05 +000022 /* Let the program abort after 3 seconds instead of leaving it deadlocked. */
23 alarm(3);
24
bart5357fcb2008-02-27 15:46:00 +000025 {
26 pthread_mutex_t m = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
27
28 printf("Recursive mutex (statically initialized).\n");
29 lock_twice(&m);
bart68d80f42008-03-08 15:03:30 +000030 pthread_mutex_destroy(&m);
bart5357fcb2008-02-27 15:46:00 +000031 }
32 {
33 pthread_mutex_t m;
34 pthread_mutexattr_t attr;
35
36 printf("Recursive mutex (initialized via mutex attributes).\n");
37 pthread_mutexattr_init(&attr);
38 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
39 pthread_mutex_init(&m, &attr);
40 pthread_mutexattr_destroy(&attr);
41 lock_twice(&m);
42 pthread_mutex_destroy(&m);
43 }
44 {
45 pthread_mutex_t m;
46 pthread_mutexattr_t attr;
47
48 printf("Error checking mutex.\n");
49 pthread_mutexattr_init(&attr);
50 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
51 pthread_mutex_init(&m, &attr);
52 pthread_mutexattr_destroy(&attr);
53 lock_twice(&m);
54 pthread_mutex_destroy(&m);
55 }
56 {
57 pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
58
59 printf("Non-recursive mutex.\n");
bart8bba1f72008-02-27 16:13:05 +000060 fflush(stdout);
bart5357fcb2008-02-27 15:46:00 +000061 lock_twice(&m);
62 }
bart8bba1f72008-02-27 16:13:05 +000063 printf("Done.\n");
bart5357fcb2008-02-27 15:46:00 +000064 return 0;
65}