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 * shall create a thread-specific data key visible to all threaads in the process. Key values 11 * provided by pthread_key_create() are opaque objects used to locate thread-specific data. 12 * Although the same key value may be used by different threads, the values bound to the key 13 * by pthread_setspecific() are maintained on a per-thread basis and persist for the life of 14 * the calling thread. 15 * 16 * Steps: 17 * 1. Define and create a key 18 * 2. Verify that you can create many threads with the same key value 19 * 20 */ 21 22 #include <pthread.h> 23 #include <stdio.h> 24 #include <stdlib.h> 25 #include <unistd.h> 26 #include "posixtest.h" 27 28 #define NUM_OF_THREADS 10 29 #define KEY_VALUE 1000 30 pthread_key_t keys[NUM_OF_THREADS]; 31 int i; 32 33 /* Thread function that sets the key to KEY_VALUE */ 34 void *a_thread_func() 35 { 36 /* Set the key to KEY_VALUE */ 37 if (pthread_setspecific(keys[i], (void *)(KEY_VALUE)) != 0) { 38 printf("Error: pthread_setspecific() failed\n"); 39 pthread_exit((void *)PTS_FAIL); 40 } 41 42 pthread_exit(0); 43 } 44 45 int main(void) 46 { 47 pthread_t new_th; 48 void *value_ptr; 49 50 /* Create a key */ 51 for (i = 0; i < NUM_OF_THREADS; i++) { 52 if (pthread_key_create(&keys[i], NULL) != 0) { 53 printf("Error: pthread_key_create() failed\n"); 54 return PTS_UNRESOLVED; 55 } 56 } 57 58 /* Create NUM_OF_THREADS threads and in the thread_func, it will 59 * use pthread_setspecific with the same KEY_VALUE */ 60 for (i = 0; i < NUM_OF_THREADS; i++) { 61 /* Create a thread */ 62 if (pthread_create(&new_th, NULL, a_thread_func, NULL) != 0) { 63 perror("Error creating thread\n"); 64 return PTS_UNRESOLVED; 65 } 66 67 /* Wait for thread to end */ 68 if (pthread_join(new_th, &value_ptr) != 0) { 69 perror("Error in pthread_join\n"); 70 return PTS_UNRESOLVED; 71 } 72 73 if (value_ptr == (void *)PTS_FAIL) { 74 printf 75 ("Test FAILED: Could not use a certain key value to set for many keys\n"); 76 return PTS_FAIL; 77 } 78 } 79 80 printf("Test PASSED\n"); 81 return PTS_PASS; 82 } 83