blob: 069c862d85f074887d831c8c27f5dbbd6928ef6a [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>
8#include <pthread.h>
9
10static void lock_twice(pthread_mutex_t* const p)
11{
12 pthread_mutex_lock(p);
13 pthread_mutex_lock(p);
14 pthread_mutex_unlock(p);
15 pthread_mutex_unlock(p);
16}
17
18int main(int argc, char** argv)
19{
bart8bba1f72008-02-27 16:13:05 +000020 /* Let the program abort after 3 seconds instead of leaving it deadlocked. */
21 alarm(3);
22
bart5357fcb2008-02-27 15:46:00 +000023 {
24 pthread_mutex_t m = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
25
26 printf("Recursive mutex (statically initialized).\n");
27 lock_twice(&m);
28 }
29 {
30 pthread_mutex_t m;
31 pthread_mutexattr_t attr;
32
33 printf("Recursive mutex (initialized via mutex attributes).\n");
34 pthread_mutexattr_init(&attr);
35 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
36 pthread_mutex_init(&m, &attr);
37 pthread_mutexattr_destroy(&attr);
38 lock_twice(&m);
39 pthread_mutex_destroy(&m);
40 }
41 {
42 pthread_mutex_t m;
43 pthread_mutexattr_t attr;
44
45 printf("Error checking mutex.\n");
46 pthread_mutexattr_init(&attr);
47 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
48 pthread_mutex_init(&m, &attr);
49 pthread_mutexattr_destroy(&attr);
50 lock_twice(&m);
51 pthread_mutex_destroy(&m);
52 }
53 {
54 pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
55
56 printf("Non-recursive mutex.\n");
bart8bba1f72008-02-27 16:13:05 +000057 fflush(stdout);
bart5357fcb2008-02-27 15:46:00 +000058 lock_twice(&m);
59 }
bart8bba1f72008-02-27 16:13:05 +000060 printf("Done.\n");
bart5357fcb2008-02-27 15:46:00 +000061 return 0;
62}