c - 冗余 __thread 和 omp threadlocal 声明

标签 c multithreading openmp portability

我正在尝试编写一些库代码,可供启用(或未启用)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/

相关文章:

c - 如何从队列中删除集合节点

c++ - 多核机器上的多个程序实例

linux - openCL 和 openMP 教程——位置?

python - 切换进出 PyFrameObjects 可以很好地实现延续吗?

C: fgets 总是 NULL

python - 如何将函数连接到主线程之外的 PyQt 信号

c# - 如何在特定核心上启动线程?

c++ - OpenMP 中的 "static"和 "dynamic"调度有什么区别?

c++ - 我在哪里可以找到 NS2 库的 cpp 文件中生成的打印信息,其中我添加了一些 cout() 函数来打印一些信息?

java - 覆盖线程池中线程的中断方法