OpenMP中的共享变量 [英] Shared variables in OpenMP
问题描述
关于OpenMP中的共享变量,我有一个非常基本的问题(也许很愚蠢).考虑以下代码:
I have a very basic question (maybe stupid) regarding shared variables in OpenMP. Consider the following code:
void main()
{
int numthreads;
#pragma omp parallel default(none) shared(numthreads)
{
numthreads = omp_get_num_threads();
printf("%d\n",numthreads);
}
}
现在,所有线程的numthreads
值都相同.是否有可能由于各个线程将相同的值写入相同的变量,该值可能会出现乱码/乱码?还是对原始数据类型的此操作保证是原子的?
Now the value of numthreads
is the same for all threads. is there a possibility that since various threads are writing the same value to the same variable, the value might get garbled/mangled ? Or is this operation on a primitive datatype guaranteed to be atomic ?
推荐答案
按照标准,这是不安全的:
As per the standard, this is not safe:
可以使用多个加载或存储指令来实现对变量的单次访问,并且 因此,对于同一变量的其他访问,不能保证是原子的. [...] 如果多个线程在不同步的情况下写入同一内存单元,包括 如上所述的原子性考虑,然后发生数据争用. [...]如果发生数据争用,则程序的结果未指定.
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 OpenMP内存模型的结构.虽然这不是最容易阅读的书,但它非常具体且非常清楚.比我在这里描述的要好得多.
I strongly recommend reading 1.4.1 Structure of the OpenMP Memory Model. While it's not the easiest read, it's very specific and quite clear. By far better than I could describe it here.
关于OpenMP中的共享变量,需要考虑两点:访问权限 atomicity 和内存临时视图 .
Two things need to be considered about shared variables in OpenMP: atomicity of access and the temporary view of memory.
这篇关于OpenMP中的共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!