multithreading - OpenMP 中的共享变量

标签 multithreading openmp shared-memory

关于 OpenMP 中的共享变量,我有一个非常基本的问题(可能很愚蠢)。考虑以下代码:

void main()
{
int numthreads;
#pragma omp parallel default(none) shared(numthreads)
 {
  numthreads = omp_get_num_threads();
  printf("%d\n",numthreads);
 }
}

现在 numthreads 的值所有线程都是一样的。是否有可能因为不同的线程将相同的值写入相同的变量,该值可能会出现乱码/损坏?或者这个对原始数据类型的操作是否保证是原子的?

最佳答案

根据标准,这是不安全的:

A single access to a variable may be implemented with multiple load or store instructions, and hence is not guaranteed to be atomic with respect to other accesses to the same variable. [...] If multiple threads write without synchronization to the same memory unit, including cases due to atomicity considerations as described above, then a data race occurs. [...] If a data race occurs then the result of the program is unspecified.



我强烈推荐阅读 1.4.1 Structure of the OpenMP Memory Model .虽然它不是最简单的阅读,但它非常具体且非常清晰。比我在这里描述的要好得多。

OpenMP 中的共享变量需要考虑两件事:访问的原子性和内存的临时 View 。

关于multithreading - OpenMP 中的共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45253445/

相关文章:

C++11 无锁自动更新 2 个变量

c++ - OpenMP:同一编译指示上的 nowait 和 reduction 子句

c - 有什么干净的方法可以让 OpenMP pragmas 与宏一起工作?

python - 在 Python 进程之间共享一个大的(只读的)二进制字符串?

c - 尝试在客户端-服务器程序中的进程之间创建共享内存段

java - 如何添加Java多线程

java - 无法解决与Java Threads相关的教科书示例

JavaFX:任务不会更新 UI

java - 使用使用 getter 和 setter 的静态字段与声明为公共(public)的静态字段之间的区别

c++ - 多线程比没有线程慢C++