OpenMP 中的共享变量
Shared variables in OpenMP
关于 OpenMP 中的共享变量,我有一个非常基本的问题(可能很愚蠢)。考虑以下代码:
void main()
{
int numthreads;
#pragma omp parallel default(none) shared(numthreads)
{
numthreads = omp_get_num_threads();
printf("%d\n",numthreads);
}
}
现在 numthreads
的值对于所有线程都是相同的。是否有可能因为各种线程将相同的值写入相同的变量,该值可能会得到garbled/mangled?或者这个对原始数据类型的操作保证是原子的?
根据标准,这不安全:
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 中的共享变量需要考虑两件事:访问的原子性和内存的临时视图。
关于 OpenMP 中的共享变量,我有一个非常基本的问题(可能很愚蠢)。考虑以下代码:
void main()
{
int numthreads;
#pragma omp parallel default(none) shared(numthreads)
{
numthreads = omp_get_num_threads();
printf("%d\n",numthreads);
}
}
现在 numthreads
的值对于所有线程都是相同的。是否有可能因为各种线程将相同的值写入相同的变量,该值可能会得到garbled/mangled?或者这个对原始数据类型的操作保证是原子的?
根据标准,这不安全:
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 中的共享变量需要考虑两件事:访问的原子性和内存的临时视图。