我正在尝试编写一些库代码,可供启用(或未启用)pthreads 的人员以及启用(或不启用)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?)
我知道这适用于我的系统(带有最新 gcc 的 Debian),但很难知道其他地方是否会出现问题,因为这些特定于编译器的声明不是 OpenMP 标准的一部分。
最佳答案
关于:
#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
即可。
关于c - 冗余 __thread 和 omp threadlocal 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38035067/