1570af302Sopenharmony_ci#include <pthread.h>
2570af302Sopenharmony_ci#include <string.h>
3570af302Sopenharmony_ci#include "test.h"
4570af302Sopenharmony_ci
5570af302Sopenharmony_ci#define TESTC(c, m) ( (c) || (t_error("%s failed (" m ")\n", #c), 0) )
6570af302Sopenharmony_ci#define TESTR(r, f, m) ( \
7570af302Sopenharmony_ci	((r) = (f)) == 0 || (t_error("%s failed: %s (" m ")\n", #f, strerror(r)), 0) )
8570af302Sopenharmony_ci
9570af302Sopenharmony_cistatic pthread_key_t k1, k2;
10570af302Sopenharmony_ci
11570af302Sopenharmony_cistatic void dtor(void *p)
12570af302Sopenharmony_ci{
13570af302Sopenharmony_ci	*(int *)p = 1;
14570af302Sopenharmony_ci}
15570af302Sopenharmony_ci
16570af302Sopenharmony_cistatic void *start(void *arg)
17570af302Sopenharmony_ci{
18570af302Sopenharmony_ci	int *p = arg;
19570af302Sopenharmony_ci	if (pthread_setspecific(k1, p) || pthread_setspecific(k2, p+1))
20570af302Sopenharmony_ci		return arg;
21570af302Sopenharmony_ci	return 0;
22570af302Sopenharmony_ci}
23570af302Sopenharmony_ci
24570af302Sopenharmony_ciint main(void)
25570af302Sopenharmony_ci{
26570af302Sopenharmony_ci	pthread_t td;
27570af302Sopenharmony_ci	int r;
28570af302Sopenharmony_ci	void *res;
29570af302Sopenharmony_ci	int foo[2], bar[2];
30570af302Sopenharmony_ci
31570af302Sopenharmony_ci	/* Test POSIX thread-specific data */
32570af302Sopenharmony_ci	TESTR(r, pthread_key_create(&k1, dtor), "failed to create key");
33570af302Sopenharmony_ci	TESTR(r, pthread_key_create(&k2, dtor), "failed to create key");
34570af302Sopenharmony_ci	foo[0] = foo[1] = 0;
35570af302Sopenharmony_ci	TESTR(r, pthread_setspecific(k1, bar), "failed to set tsd");
36570af302Sopenharmony_ci	TESTR(r, pthread_setspecific(k2, bar+1), "failed to set tsd");
37570af302Sopenharmony_ci	TESTR(r, pthread_create(&td, 0, start, foo), "failed to create thread");
38570af302Sopenharmony_ci	TESTR(r, pthread_join(td, &res), "failed to join");
39570af302Sopenharmony_ci	TESTC(res == 0, "pthread_setspecific failed in thread");
40570af302Sopenharmony_ci	TESTC(foo[0] == 1, "dtor failed to run");
41570af302Sopenharmony_ci	TESTC(foo[1] == 1, "dtor failed to run");
42570af302Sopenharmony_ci	TESTC(pthread_getspecific(k1) == bar, "tsd corrupted");
43570af302Sopenharmony_ci	TESTC(pthread_getspecific(k2) == bar+1, "tsd corrupted");
44570af302Sopenharmony_ci	TESTR(r, pthread_setspecific(k1, 0), "failed to clear tsd");
45570af302Sopenharmony_ci	TESTR(r, pthread_setspecific(k2, 0), "failed to clear tsd");
46570af302Sopenharmony_ci	TESTR(r, pthread_key_delete(k1), "failed to destroy key");
47570af302Sopenharmony_ci	TESTR(r, pthread_key_delete(k2), "failed to destroy key");
48570af302Sopenharmony_ci	return t_status;
49570af302Sopenharmony_ci}
50