可移植的静态线程局部存储修饰符


主流 C、C++ 编译器在主流平台下通常都通过语言扩展来支持静态线程局部存储,用户可以通过在静态变量前简单地添加一个修饰符使其被静态地添加到 TLS 索引中。然而,不同的编译器支持不同的修饰方式,有时为了可移植性,就需要类似下面这样的预编译指令,根据当前使用的编译器来决定如何定义修饰符。

#if defined(__GNUC__) || defined(__SUNPRO_C) || defined(__xlc__)
# define THREAD_LOCAL __thread
#elif defined(_MSC_VER) || defined(__BORLANDC__) || defined(__DMC__)
# define THREAD_LOCAL __declspec(thread)
#elif defined(__INTEL_COMPILER)
# ifdef _WIN32
#   define THREAD_LOCAL __declspec(thread)
# else
#   define THREAD_LOCAL __thread
# endif
#else
# error "Unsupported compiler."
#endif

之后用 static THREAD_LOCAL 修饰变量即可。

Leave a comment