当前位置: C语言 -- 标准库 -- <threads.h> -- tss_t

tss_t类型


描述:

该类型是保存线程专属存储指针标识符的完整对象类型。


范例:
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 
/*类型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;
}


输出:

Be slow to promise and quick to perform.

Better an empty purse than an empty head.

Birds of a feather flock together.

注:使用Pelles C编译。


相关内容:
mtx_t 保存互斥标识符的完整对象类型。
cnd_t 保存条件变量标识符的完整对象类型。
thrd_t 保存线程标识符的完整对象类型。