关于 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/