冗余__thread和omp threadlocal声明

时间:2016-06-26 03:54:23

标签: c multithreading openmp portability

我正在尝试编写一些可能由启用(或不启用)pthread的人使用的库代码,以及有openmp支持(或不支持)的人。我有一些变量,我真的想要在线程本地存储。指定这两次是否有任何潜在的危害,例如

#ifdef __GNUC__
# define PREFIX __thread
#elif __STDC_VERSION__ >= 201112L
# define PREFIX _Thread_local
#elif defined(_MSC_VER)
# define PREFIX __declspec(thread)
#else
# define PREFIX
#endif

PREFIX int var = 10;
#pragma omp threadprivate(var)

(注意,找出TLS前缀的业务来自How to declare a variable as thread local portably?

我知道这可以在我的系统上运行(Debian和最近的gcc),但很难知道其他地方是否会出错,因为这些特定于编译器的声明不属于OpenMP标准。

1 个答案:

答案 0 :(得分:1)

怎么样:

#if __STDC_VERSION__ >= 201112L
# define PREFIX _Thread_local
#elif defined(__GNUC__)
# define PREFIX __thread
#elif defined(_MSC_VER)
# define PREFIX __declspec(thread)
#else
# define PREFIX
#endif

PREFIX int var = 10;
#if !PREFIX
#ifdef _OPENMP
#pragma omp threadprivate(var)
#else
#error "Failure to put variable into TLS"
#endif
#endif

GCC并不介意过度指定,因为__thread无论如何都是隐式#pragma omp threadprivate

不要担心编译器可能不是这种情况,只需有条件地使用OpenMP threadprivate