bart | 5357fcb | 2008-02-27 15:46:00 +0000 | [diff] [blame^] | 1 | /** Initialize a recursive mutex and lock it twice. |
| 2 | * No error messages may be printed. |
| 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 | { |
| 20 | { |
| 21 | pthread_mutex_t m = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; |
| 22 | |
| 23 | printf("Recursive mutex (statically initialized).\n"); |
| 24 | lock_twice(&m); |
| 25 | } |
| 26 | { |
| 27 | pthread_mutex_t m; |
| 28 | pthread_mutexattr_t attr; |
| 29 | |
| 30 | printf("Recursive mutex (initialized via mutex attributes).\n"); |
| 31 | pthread_mutexattr_init(&attr); |
| 32 | pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); |
| 33 | pthread_mutex_init(&m, &attr); |
| 34 | pthread_mutexattr_destroy(&attr); |
| 35 | lock_twice(&m); |
| 36 | pthread_mutex_destroy(&m); |
| 37 | } |
| 38 | { |
| 39 | pthread_mutex_t m; |
| 40 | pthread_mutexattr_t attr; |
| 41 | |
| 42 | printf("Error checking mutex.\n"); |
| 43 | pthread_mutexattr_init(&attr); |
| 44 | pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP); |
| 45 | pthread_mutex_init(&m, &attr); |
| 46 | pthread_mutexattr_destroy(&attr); |
| 47 | lock_twice(&m); |
| 48 | pthread_mutex_destroy(&m); |
| 49 | } |
| 50 | { |
| 51 | pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; |
| 52 | |
| 53 | printf("Non-recursive mutex.\n"); |
| 54 | lock_twice(&m); |
| 55 | } |
| 56 | return 0; |
| 57 | } |