blob: eab2eec51d3afc96034bd965fe96c0d5950e1554 [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);
30 }
31 {
32 pthread_mutex_t m;
33 pthread_mutexattr_t attr;
34
35 printf("Recursive mutex (initialized via mutex attributes).\n");
36 pthread_mutexattr_init(&attr);
37 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
38 pthread_mutex_init(&m, &attr);
39 pthread_mutexattr_destroy(&attr);
40 lock_twice(&m);
41 pthread_mutex_destroy(&m);
42 }
43 {
44 pthread_mutex_t m;
45 pthread_mutexattr_t attr;
46
47 printf("Error checking mutex.\n");
48 pthread_mutexattr_init(&attr);
49 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
50 pthread_mutex_init(&m, &attr);
51 pthread_mutexattr_destroy(&attr);
52 lock_twice(&m);
53 pthread_mutex_destroy(&m);
54 }
55 {
56 pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
57
58 printf("Non-recursive mutex.\n");
bart8bba1f72008-02-27 16:13:05 +000059 fflush(stdout);
bart5357fcb2008-02-27 15:46:00 +000060 lock_twice(&m);
61 }
bart8bba1f72008-02-27 16:13:05 +000062 printf("Done.\n");
bart5357fcb2008-02-27 15:46:00 +000063 return 0;
64}