如何将变量声明为本地可移植的线程?

时间:2013-08-18 10:49:21

标签: c gcc portability c11 thread-local-storage

C11引入了_Thread_local存储类说明符,可以与staticextern存储类说明符结合使用,将变量声明为线程局部。 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

1 个答案:

答案 0 :(得分:11)

information from Wikipedia与此list of compiler macros相结合,我提出了以下(未经测试)版本:

#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