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
30pthread_key_t keys[NUM_OF_THREADS];
31int i;
32
33/* Thread function that sets the key to KEY_VALUE */
34void *a_thread_func()
35{
36	/* Set the key to KEY_VALUE */
37	if(pthread_setspecific(keys[i], (void *)(KEY_VALUE)) != 0)
38	{
39		printf("Error: pthread_setspecific() failed\n");
40		pthread_exit((void*)PTS_FAIL);
41	}
42
43	pthread_exit(0);
44	return NULL;
45}
46
47int main()
48{
49	pthread_t new_th;
50	void *value_ptr;
51
52	/* Create a key */
53	for(i = 0;i<NUM_OF_THREADS;i++)
54	{
55		if(pthread_key_create(&keys[i], NULL) != 0)
56		{
57			printf("Error: pthread_key_create() failed\n");
58			return PTS_UNRESOLVED;
59		}
60	}
61
62	/* Create NUM_OF_THREADS threads and in the thread_func, it will
63	 * use pthread_setspecific with the same KEY_VALUE */
64	for(i = 0;i<NUM_OF_THREADS;i++)
65	{
66		/* Create a thread */
67		if(pthread_create(&new_th, NULL, a_thread_func, NULL) != 0)
68		{
69			perror("Error creating thread\n");
70			return PTS_UNRESOLVED;
71		}
72
73		/* Wait for thread to end */
74		if(pthread_join(new_th, &value_ptr) != 0)
75		{
76			perror("Error in pthread_join\n");
77			return PTS_UNRESOLVED;
78		}
79
80		if(value_ptr == (void*) PTS_FAIL)
81		{
82			printf("Test FAILED: Could not use a certain key value to set for many keys\n");
83			return PTS_FAIL;
84		}
85	}
86
87	printf("Test PASSED\n");
88	return PTS_PASS;
89}
90