bart | 8bba1f7 | 2008-02-27 16:13:05 +0000 | [diff] [blame] | 1 | /** Initialize several kinds of mutexes and lock each mutex twice. |
| 2 | * Note: locking a regular mutex twice causes a deadlock. |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | #define _GNU_SOURCE |
| 6 | |
| 7 | #include <stdio.h> |
bart | 4240ff3 | 2008-02-27 17:41:22 +0000 | [diff] [blame^] | 8 | #include <unistd.h> |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 9 | #include <pthread.h> |
| 10 | |
bart | 4240ff3 | 2008-02-27 17:41:22 +0000 | [diff] [blame^] | 11 | |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 12 | static 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 | |
| 20 | int main(int argc, char** argv) |
| 21 | { |
bart | 8bba1f7 | 2008-02-27 16:13:05 +0000 | [diff] [blame] | 22 | /* Let the program abort after 3 seconds instead of leaving it deadlocked. */ |
| 23 | alarm(3); |
| 24 | |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 25 | { |
| 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"); |
bart | 8bba1f7 | 2008-02-27 16:13:05 +0000 | [diff] [blame] | 59 | fflush(stdout); |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 60 | lock_twice(&m); |
| 61 | } |
bart | 8bba1f7 | 2008-02-27 16:13:05 +0000 | [diff] [blame] | 62 | printf("Done.\n"); |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 63 | return 0; |
| 64 | } |