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> |
| 8 | #include <pthread.h> |
| 9 | |
| 10 | static 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 | |
| 18 | int main(int argc, char** argv) |
| 19 | { |
bart | 8bba1f7 | 2008-02-27 16:13:05 +0000 | [diff] [blame^] | 20 | /* Let the program abort after 3 seconds instead of leaving it deadlocked. */ |
| 21 | alarm(3); |
| 22 | |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 23 | { |
| 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"); |
bart | 8bba1f7 | 2008-02-27 16:13:05 +0000 | [diff] [blame^] | 57 | fflush(stdout); |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 58 | lock_twice(&m); |
| 59 | } |
bart | 8bba1f7 | 2008-02-27 16:13:05 +0000 | [diff] [blame^] | 60 | printf("Done.\n"); |
bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame] | 61 | return 0; |
| 62 | } |