【问题标题】:How to declare a variable as thread local portably?如何将变量声明为可移植的线程本地?
【发布时间】:2013-08-18 10:49:20
【问题描述】:

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

【问题讨论】:

  • 在 MSVC 中,写成__declspec( thread )(见msdn.microsoft.com/en-us/library/4ax54352.aspx
  • @KingsIndian Jupp。这就是为什么我问定义这个宏的最佳方法是什么。
  • @KingsIndian Generic 可能包含一些愚蠢编译器的特殊情况。

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


【解决方案1】:

结合information from Wikipedialist 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

【讨论】:

  • 嘿,这很好。非常感谢!
猜你喜欢
  • 2014-09-03
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
相关资源
最近更新 更多