blob: ad79b63fd3c992a2ceab0f76bcf4752202dfe172 [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>
bart85569572008-05-03 09:15:25 +000010#include "../../config.h"
bart5357fcb2008-02-27 15:46:00 +000011
bart4240ff32008-02-27 17:41:22 +000012
bart5357fcb2008-02-27 15:46:00 +000013static void lock_twice(pthread_mutex_t* const p)
14{
15 pthread_mutex_lock(p);
16 pthread_mutex_lock(p);
17 pthread_mutex_unlock(p);
18 pthread_mutex_unlock(p);
19}
20
21int main(int argc, char** argv)
22{
bart8bba1f72008-02-27 16:13:05 +000023 /* Let the program abort after 3 seconds instead of leaving it deadlocked. */
24 alarm(3);
bart85569572008-05-03 09:15:25 +000025
26#if defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
bart5357fcb2008-02-27 15:46:00 +000027 {
28 pthread_mutex_t m = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
29
30 printf("Recursive mutex (statically initialized).\n");
31 lock_twice(&m);
bart68d80f42008-03-08 15:03:30 +000032 pthread_mutex_destroy(&m);
bart85569572008-05-03 09:15:25 +000033 }
34#endif
35#if defined(HAVE_PTHREAD_MUTEX_RECURSIVE_NP)
bart5357fcb2008-02-27 15:46:00 +000036 {
37 pthread_mutex_t m;
38 pthread_mutexattr_t attr;
39
40 printf("Recursive mutex (initialized via mutex attributes).\n");
41 pthread_mutexattr_init(&attr);
42 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
43 pthread_mutex_init(&m, &attr);
44 pthread_mutexattr_destroy(&attr);
45 lock_twice(&m);
46 pthread_mutex_destroy(&m);
bart85569572008-05-03 09:15:25 +000047 }
48#endif
49#if defined(HAVE_PTHREAD_MUTEX_ERRORCHECK_NP)
bart5357fcb2008-02-27 15:46:00 +000050 {
51 pthread_mutex_t m;
52 pthread_mutexattr_t attr;
53
54 printf("Error checking mutex.\n");
55 pthread_mutexattr_init(&attr);
56 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
57 pthread_mutex_init(&m, &attr);
58 pthread_mutexattr_destroy(&attr);
59 lock_twice(&m);
bart85569572008-05-03 09:15:25 +000060 pthread_mutex_destroy(&m);
61 }
62#endif
bart5357fcb2008-02-27 15:46:00 +000063 {
64 pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
65
66 printf("Non-recursive mutex.\n");
bart8bba1f72008-02-27 16:13:05 +000067 fflush(stdout);
bart5357fcb2008-02-27 15:46:00 +000068 lock_twice(&m);
bart85569572008-05-03 09:15:25 +000069 }
bart8bba1f72008-02-27 16:13:05 +000070 printf("Done.\n");
bart5357fcb2008-02-27 15:46:00 +000071 return 0;
72}