1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
|
/*
* File: tsd1.c
*
* Test Synopsis:
* - Thread Specific Data (TSD) key creation and destruction.
*
* Description:
* -
*
* Test Method (validation or falsification):
* - validation
*
* Requirements Tested:
* - keys are created for each existing thread including the main thread
* - keys are created for newly created threads
* - keys are thread specific
* - destroy routine is called on each thread exit including the main thread
*
* Features Tested:
* -
*
* Cases Tested:
* -
*
* Environment:
* -
*
* Input:
* - none
*
* Output:
* - text to stdout
*
* Assumptions:
* - already validated: pthread_create()
* pthread_once()
* - main thread also has a POSIX thread identity
*
* Pass Criteria:
* - stdout matches file reference/tsd1.out
*
* Fail Criteria:
* - fails to match file reference/tsd1.out
* - output identifies failed component
*/
#include <pthread.h>
#include <stdio.h>
pthread_key_t key = NULL;
pthread_once_t key_once = PTHREAD_ONCE_INIT;
void
destroy_key(void * arg)
{
/* arg is not NULL if we get to here. */
printf("SUCCESS: %s: destroying key.\n", (char *) arg);
free((char *) arg);
}
void
make_key(void)
{
if (pthread_key_create(&key, destroy_key) != 0)
{
printf("Key create failed\n");
exit(1);
}
}
void
setkey(void * arg)
{
void * ptr;
if ((ptr = pthread_getspecific(key)) != NULL)
{
printf("ERROR: Thread %d, Key not initialised to NULL\n",
(int) arg);
exit(1);
}
else
{
ptr = (void *) malloc(80);
sprintf((char *) ptr, "Thread %d Key",
(int) arg);
(void) pthread_setspecific(key, ptr);
}
if ((ptr = pthread_getspecific(key)) == NULL)
{
printf("FAILED: Thread %d Key value set or get failed.\n",
(int) arg);
exit(1);
}
else
{
printf("SUCCESS: Thread %d Key value set and get succeeded.\n",
(int) arg);
printf("SUCCESS: %s: exiting thread.\n", (char *) ptr);
}
}
void *
mythread(void * arg)
{
while (key == NULL)
{
}
printf("Thread %d, Key created\n", (int) arg);
setkey(arg);
return 0;
/* Exiting the thread will call the key destructor. */
}
int
main()
{
int rc;
int t;
pthread_t thread[10];
for (t = 0; t < 5; t++)
{
rc = pthread_create(&thread[t], NULL, mythread, (void *) (t + 1));
printf("pthread_create returned %d\n", rc);
}
(void) pthread_once(&key_once, make_key);
/* Test main thread key. */
setkey((void *) 0);
Sleep(500);
for (t = 5; t < 10; t++)
{
rc = pthread_create(&thread[t], NULL, mythread, (void *) (t + 1));
printf("pthread_create returned %d\n", rc);
}
Sleep(2000);
return 0;
}
|