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); |
bart | 68d80f4 | 2008-03-08 15:03:30 +0000 | [diff] [blame^] | 30 | pthread_mutex_destroy(&m); |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 31 | } |
| 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"); |
bart | 8bba1f7 | 2008-02-27 16:13:05 +0000 | [diff] [blame] | 60 | fflush(stdout); |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 61 | lock_twice(&m); |
| 62 | } |
bart | 8bba1f7 | 2008-02-27 16:13:05 +0000 | [diff] [blame] | 63 | printf("Done.\n"); |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 64 | return 0; |
| 65 | } |