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

thread_local宏


概要:
#include <threads.h>
#define thread_local _Thread_local

描述:

该宏会扩展为C语言关键词_Thread_local,表示线程存储期限。

具有块作用域对象的声明中,如果声明说明符包含_Thread_local,声明说明符还应该包含static或者extern。如果在标识符的任一声明中出现了_Thread_local声明说明符,该标识符的所有声明中都应该使用_Thread_local声明说明符。_Thread_local声明说明符不能用于函数声明。


使用_Thread_local声明说明符声明的对象具有线程存储期限。该对象的生存期是其声明线程的整个执行过程,并且其值在线程启动时初始化。不同线程中相同标识符标识的是不同对象;在表达式中使用标识符是指使用与评估表达式的线程相关联的对象。尝试从与对象关联的线程以外的线程访问具有线程存储期限的对象,结果将由实现定义。


ISO/IEC 9899:2018标准及以前标准中,thread_local是<threads.h>头文件中定义的宏;但ISO/IEC 9899:2024标准中,thread_local是C语言关键词;并且根据ISO/IEC 9899:2024标准,_Thread_local已经过时,不建议在新代码中使用。


范例:
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 
/*宏thread_local范例*/

#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif

#include <stdio.h>
#include <stdlib.h>
#include <threads.h>

#define THREADS 3

_Thread_local int threadLocal = 0;

/*新线程中执行的函数。*/
int func(void *arg)
{
    threadLocal = *((int *)arg)*5;
    printf("Thread %d\nValue of threadLocal: %d\nAddress of threadLocal: %p\n\n",\
           *((int *)arg), threadLocal, &threadLocal);
    
    return 0;
}

int main(void)
{
    thrd_t threadId[THREADS];
    int arr[] = {1, 2, 3};
    
    /*创建新线程。*/
    for(int i=0; i<THREADS; ++i)
    {
        if(thrd_create((threadId+i), func, (arr+i)) != thrd_success)
        {
            perror("thrd_create");
            exit(EXIT_FAILURE);
        }
    }
    
    /*连接线程。*/
    for(int i=0; i<THREADS; ++i)
        thrd_join(threadId[i], NULL);
    
    return 0;
}


输出:

Thread 1

Value of threadLocal: 5

Address of threadLocal: 00000272bdc43200

 

Thread 2

Value of threadLocal: 10

Address of threadLocal: 00000272bdc430d0

 

Thread 3

Value of threadLocal: 15

Address of threadLocal: 00000272bdc42be0


相关内容:
tss_t 保存线程专属存储指针标识符的完整对象类型。


主要参考资料:

1、ISO/IEC 9899:2024

2、ISO/IEC 9899:2018