本文介绍了如何将变量声明为线程局部可移植?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C11引入了 _Thread_local
存储类说明可在联合与静态
和<$ C $使用C> EXTERN 存储类声明来声明一个变量作为线程局部。 GNU C编译器套件实现了存储类说明 __线程
用相同的相同的语义。
不幸的是我没有找到任何编译器(我试过GCC,铛和太阳录音室),真正实现 _Thread_local
关键字。我目前使用下面的结构来声明一个关键字 thread_local
:
/ *从GCC还C11不知道_Thread_local * /
#IFDEF __GNUC__
#定义thread_local __thread
#elif指令__STDC_VERSION__&GT; = 201112L
#定义thread_local _Thread_local
#其他
#错误不知道如何定义thread_local
#万一
我知道这可能不与MSVC和其他编译器。任何人都可以建议我一个更好的方法,在某种程度上,它的作品在尽可能多的编译器尽可能声明 thread_local
?
修改
建议微软的Visual C允许 __ declspec(线程)
。这是更新的宏定义:
/ *从GCC还C11不知道_Thread_local * /
#IFDEF __GNUC__
#定义thread_local __thread
#elif指令__STDC_VERSION__&GT; = 201112L
#定义thread_local _Thread_local
#elif指令定义(_MSC_VER)
#定义thread_local __declspec(线程)
#其他
#错误不能定义thread_local
#万一
解决方案
维基百科的与,我想出了以下(未经测试)版本的编译器宏这个名单
的#ifndef thread_local
#如果__STDC_VERSION__&GT; = 201112&放大器;&安培; !定义__STDC_NO_THREADS__
#定义thread_local _Thread_local
#ELIF定义_WIN32&放大器;&安培; (\\
定义_MSC_VER || \\
定义__ICL || \\
定义__DMC__ || \\
定义__BORLANDC__)
#定义thread_local __declspec(线程)
/ *注意,ICC(Linux版)和锵被覆盖__GNUC__ * /
#ELIF定义__GNUC__ || \\
定义__SUNPRO_C || \\
定义__xlC__
#定义thread_local __thread
其他#
#错误无法定义thread_local
# 万一
#万一
/* gcc doesn't know _Thread_local from C11 yet */
#ifdef __GNUC__
# define thread_local __thread
#elif __STDC_VERSION__ >= 201112L
# define thread_local _Thread_local
#else
# error Don't know how to define thread_local
#endif
Edit
Christoph suggested that Microsoft Visual C allows __declspec(thread)
. This is the updated macro definition:
/* gcc doesn't know _Thread_local from C11 yet */
#ifdef __GNUC__
# define thread_local __thread
#elif __STDC_VERSION__ >= 201112L
# define thread_local _Thread_local
#elif defined(_MSC_VER)
# define thread_local __declspec(thread)
#else
# error Cannot define thread_local
#endif
解决方案
Combining information from Wikipedia with this list of compiler macros, I came up with the following (untested) version:
#ifndef thread_local
# if __STDC_VERSION__ >= 201112 && !defined __STDC_NO_THREADS__
# define thread_local _Thread_local
# elif defined _WIN32 && ( \
defined _MSC_VER || \
defined __ICL || \
defined __DMC__ || \
defined __BORLANDC__ )
# define thread_local __declspec(thread)
/* note that ICC (linux) and Clang are covered by __GNUC__ */
# elif defined __GNUC__ || \
defined __SUNPRO_C || \
defined __xlC__
# define thread_local __thread
# else
# error "Cannot define thread_local"
# endif
#endif
这篇关于如何将变量声明为线程局部可移植?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!