如何可移植地将变量声明为线程局部变量?

问题描述 投票:0回答:1

C11 引入了

_Thread_local
存储类说明符,它可以与
static
extern
存储类说明符结合使用,将变量声明为线程局部变量。 GNU C 编译器套件实现了具有相同语义的存储类说明符
__thread

不幸的是,我没有找到任何实际实现

_Thread_local
关键字的编译器(我尝试过 gcc、clang 和 SUN studio)。我目前使用以下构造来声明关键字
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

我知道这可能不适用于 MSVC 和其他编译器。有人可以建议我一个更好的方法来声明

thread_local
并使其在尽可能多的编译器中工作吗?

编辑

Christoph 建议 Microsoft Visual C 允许

__declspec(thread)
。这是更新后的宏定义:

/* 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
c gcc portability c11 thread-local-storage
1个回答
14
投票

结合来自维基百科的信息与这个编译器宏列表,我想出了以下(未经测试的)版本:

#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 __hpux || \
       defined __xlC__
#  define thread_local __thread
# else
#  error "Cannot define thread_local"
# endif
#endif
© www.soinside.com 2019 - 2024. All rights reserved.