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 funciton */ 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 { 47 printf("Error: pthread_setspecific() failed\n"); 48 pthread_exit((void*) PTS_UNRESOLVED); 49 } 50 51 /* The thread ends here, the destructor for the key should now be called after this */ 52 pthread_exit(0); 53 return NULL; 54} 55 56int main() 57{ 58 pthread_t new_th; 59 60 /* Inialize the destructor flag */ 61 dest_cnt = 0; 62 63 /* Create a key with a destructor function */ 64 if(pthread_key_create(&key, dest_func) != 0) 65 { 66 printf("Error: pthread_key_create() failed\n"); 67 pthread_exit((void*) PTS_UNRESOLVED); 68 } 69 70 /* Create a thread */ 71 if(pthread_create(&new_th, NULL, a_thread_func, NULL) != 0) 72 { 73 perror("Error creating thread\n"); 74 return PTS_UNRESOLVED; 75 } 76 77 /* Wait for the thread's return */ 78 if(pthread_join(new_th, NULL) != 0) 79 { 80 perror("Error in pthread_join()\n"); 81 return PTS_UNRESOLVED; 82 } 83 84 /* Check if the destructor was called */ 85 if(dest_cnt == 0) 86 { 87 printf("Test FAILED: Destructor not called\n"); 88 return PTS_FAIL; 89 } 90 91 printf("Test PASSED\n"); 92 return PTS_PASS; 93} 94