/*类型tss_t范例*/
#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <threads.h>
#define THREADS 3 //线程数。
tss_t key;
/*定义析构函数。*/
void destructor(void *arg)
{
free(arg);
}
/*新线程中执行的函数。*/
int func(void *arg)
{
char *ptr = (char *)arg;
size_t size = strlen(ptr) + 1;
tss_set(key, malloc(size));
strcpy((char *)tss_get(key), ptr);
printf("%s\n", (char *)tss_get(key));
thrd_exit(0);
}
int main(void)
{
thrd_t threadId[THREADS];
char *str[THREADS] = {"Be slow to promise and quick to perform.", \
"Better an empty purse than an empty head.", \
"Birds of a feather flock together."};
/*创建线程专属存储指针。*/
if(tss_create(&key, destructor) != thrd_success)
{
perror("tss_create");
exit(EXIT_FAILURE);
}
/*创建线程。*/
for(int i=0; i<THREADS; ++i)
{
if(thrd_create(&threadId[i], func, str[i]) != thrd_success)
{
perror("thrd_create");
exit(EXIT_FAILURE);
}
}
/*连接线程。*/
for(int i=0; i<THREADS; ++i)
thrd_join(threadId[i], NULL);
/*释放线程专属存储所用资源。*/
tss_delete(key);
return 0;
}
|