bart | 505a496 | 2009-07-04 12:20:04 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Test program for verifying whether pthread cleanup handlers are invoked |
| 3 | * correctly. |
| 4 | */ |
| 5 | |
| 6 | |
| 7 | #include <stdbool.h> |
| 8 | #include <stdio.h> |
| 9 | #include <unistd.h> |
| 10 | #include <pthread.h> |
| 11 | #include <stdlib.h> |
| 12 | |
| 13 | |
bart | 9ed94aa | 2009-07-11 15:02:27 +0000 | [diff] [blame] | 14 | static pthread_mutex_t s_mutex; |
bart | 505a496 | 2009-07-04 12:20:04 +0000 | [diff] [blame] | 15 | |
| 16 | |
| 17 | static void cleanup_handler(void* param) |
| 18 | { |
| 19 | fprintf(stderr, "Cleanup handler has been called.\n"); |
bart | 9ed94aa | 2009-07-11 15:02:27 +0000 | [diff] [blame] | 20 | pthread_mutex_unlock(&s_mutex); |
bart | 505a496 | 2009-07-04 12:20:04 +0000 | [diff] [blame] | 21 | } |
| 22 | |
| 23 | static void* f(void *p) |
| 24 | { |
bart | 9ed94aa | 2009-07-11 15:02:27 +0000 | [diff] [blame] | 25 | if (pthread_mutex_lock(&s_mutex) != 0) |
bart | 505a496 | 2009-07-04 12:20:04 +0000 | [diff] [blame] | 26 | { |
bart | 9ed94aa | 2009-07-11 15:02:27 +0000 | [diff] [blame] | 27 | fprintf(stderr, "pthread_mutex_lock()\n"); |
bart | 505a496 | 2009-07-04 12:20:04 +0000 | [diff] [blame] | 28 | exit(1); |
| 29 | } |
| 30 | |
| 31 | pthread_cleanup_push(cleanup_handler, NULL); |
| 32 | pthread_exit(0); |
| 33 | pthread_cleanup_pop(true); |
| 34 | } |
| 35 | |
| 36 | |
| 37 | int main() |
| 38 | { |
| 39 | pthread_t pt1, pt2; |
| 40 | |
| 41 | // Make sure the program exits in case a deadlock has been triggered. |
bart | 811b60e | 2011-12-13 07:49:30 +0000 | [diff] [blame] | 42 | alarm(20); |
bart | 505a496 | 2009-07-04 12:20:04 +0000 | [diff] [blame] | 43 | |
bart | 9ed94aa | 2009-07-11 15:02:27 +0000 | [diff] [blame] | 44 | if (pthread_mutex_init(&s_mutex, NULL) != 0) |
bart | 505a496 | 2009-07-04 12:20:04 +0000 | [diff] [blame] | 45 | { |
bart | 9ed94aa | 2009-07-11 15:02:27 +0000 | [diff] [blame] | 46 | fprintf(stderr, "pthread_mutex_init()\n"); |
bart | 505a496 | 2009-07-04 12:20:04 +0000 | [diff] [blame] | 47 | exit(1); |
| 48 | } |
| 49 | if (pthread_create(&pt1, NULL, f, NULL) != 0) |
| 50 | { |
| 51 | fprintf(stderr, "pthread_create()\n"); |
| 52 | exit(1); |
| 53 | } |
| 54 | if (pthread_create(&pt2, NULL, f, NULL) != 0) |
| 55 | { |
| 56 | fprintf(stderr, "pthread_create()\n"); |
| 57 | exit(1); |
| 58 | } |
| 59 | |
| 60 | pthread_join(pt1, 0); |
| 61 | pthread_join(pt2, 0); |
| 62 | |
| 63 | fprintf(stderr, "Test succeeded.\n"); |
| 64 | |
| 65 | return 0; |
| 66 | } |