bart | 995e36d | 2012-12-24 10:23:16 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Invoke pthread_cond_destroy() on a condition variable that is being waited |
| 3 | * upon. |
| 4 | */ |
| 5 | |
| 6 | #include <assert.h> |
| 7 | #include <errno.h> |
| 8 | #include <stdio.h> // printf() |
| 9 | #include <pthread.h> |
| 10 | |
| 11 | static pthread_mutex_t s_mutex; |
| 12 | static pthread_cond_t s_cond; |
| 13 | static int s_i; |
| 14 | |
| 15 | static const char* err_to_str(int errnum) |
| 16 | { |
| 17 | switch (errnum) { |
| 18 | case 0: return "success"; |
| 19 | case EBUSY: return "EBUSY"; |
| 20 | case EINVAL: return "EINVAL"; |
| 21 | default: return "?"; |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | static void* thread_func(void* thread_arg) |
| 26 | { |
| 27 | pthread_mutex_lock(&s_mutex); |
| 28 | s_i = 1; |
| 29 | pthread_cond_signal(&s_cond); |
| 30 | while (s_i == 1) |
| 31 | pthread_cond_wait(&s_cond, &s_mutex); |
| 32 | pthread_mutex_unlock(&s_mutex); |
| 33 | |
| 34 | return 0; |
| 35 | } |
| 36 | |
| 37 | int main(int argc, char** argv) |
| 38 | { |
| 39 | pthread_t threadid; |
| 40 | int ret; |
| 41 | |
| 42 | pthread_mutex_init(&s_mutex, 0); |
| 43 | pthread_cond_init(&s_cond, 0); |
| 44 | |
| 45 | pthread_create(&threadid, 0, thread_func, 0); |
| 46 | |
| 47 | pthread_mutex_lock(&s_mutex); |
| 48 | while (s_i == 0) |
| 49 | pthread_cond_wait(&s_cond, &s_mutex); |
| 50 | pthread_mutex_unlock(&s_mutex); |
| 51 | |
| 52 | ret = pthread_cond_destroy(&s_cond); |
| 53 | fprintf(stderr, "First pthread_cond_destroy() call returned %s.\n", |
| 54 | err_to_str(ret)); |
| 55 | |
| 56 | pthread_mutex_lock(&s_mutex); |
| 57 | s_i = 2; |
| 58 | pthread_cond_signal(&s_cond); |
| 59 | pthread_mutex_unlock(&s_mutex); |
| 60 | |
| 61 | pthread_join(threadid, 0); |
| 62 | |
| 63 | ret = pthread_cond_destroy(&s_cond); |
| 64 | fprintf(stderr, "Second pthread_cond_destroy() call returned %s.\n", |
| 65 | err_to_str(ret)); |
| 66 | pthread_mutex_destroy(&s_mutex); |
| 67 | |
| 68 | return 0; |
| 69 | } |