1/* 2 * Copyright (c) 2002, Intel Corporation. All rights reserved. 3 * Created by: bing.wei.liu REMOVE-THIS AT intel DOT com 4 * This file is licensed under the GPL license. For the full content 5 * of this license, see the COPYING file at the top level of this 6 * source tree. 7 8 * Test that pthread_key_create() 9 * 10 * An optional destructor function may be associated with each key value. At thread exit, if 11 * a key value has a non-NULL destructor pointer, and the thread has a non-NULL value associated 12 * with that key, the value of the key is set to NULL, and then the function pointed to is called 13 * with the previously associated value as its sole argument. The order of destructor calls is 14 * unspecified if more than one destructor exists for a thread when it exits. 15 * 16 * Steps: 17 * 1. Define an array of keys 18 * 2. Use pthread_key_create() and create those keys 19 * 3. Verify that you can set and get specific values for those keys without errors. 20 * 21 */ 22 23#include <pthread.h> 24#include <stdio.h> 25#include <stdlib.h> 26#include <unistd.h> 27#include "posixtest.h" 28 29#define KEY_VALUE 1000 30 31pthread_key_t key; 32int dest_cnt; 33 34/* Destructor function */ 35void dest_func(void *p) 36{ 37 dest_cnt++; 38} 39 40/* Thread function */ 41void *a_thread_func() 42{ 43 44 /* Set the value of the key to a value */ 45 if (pthread_setspecific(key, (void *)(KEY_VALUE)) != 0) { 46 printf("Error: pthread_setspecific() failed\n"); 47 pthread_exit((void *)PTS_UNRESOLVED); 48 } 49 50 /* The thread ends here, the destructor for the key should now be called after this */ 51 pthread_exit(0); 52} 53 54int main(void) 55{ 56 pthread_t new_th; 57 58 /* Initialize the destructor flag */ 59 dest_cnt = 0; 60 61 /* Create a key with a destructor function */ 62 if (pthread_key_create(&key, dest_func) != 0) { 63 printf("Error: pthread_key_create() failed\n"); 64 pthread_exit((void *)PTS_UNRESOLVED); 65 } 66 67 /* Create a thread */ 68 if (pthread_create(&new_th, NULL, a_thread_func, NULL) != 0) { 69 perror("Error creating thread\n"); 70 return PTS_UNRESOLVED; 71 } 72 73 /* Wait for the thread's return */ 74 if (pthread_join(new_th, NULL) != 0) { 75 perror("Error in pthread_join()\n"); 76 return PTS_UNRESOLVED; 77 } 78 79 /* Check if the destructor was called */ 80 if (dest_cnt == 0) { 81 printf("Test FAILED: Destructor not called\n"); 82 return PTS_FAIL; 83 } 84 85 printf("Test PASSED\n"); 86 return PTS_PASS; 87} 88