问题描述
我试图了解OpenMP中#pragma omp critical
和#pragma omp single
之间的确切区别:
I am trying to understand the exact difference between #pragma omp critical
and #pragma omp single
in OpenMP:
Microsoft对这些的定义是:
Microsoft definitions for these are:
- 单个:让您指定应在以下位置执行一段代码单个线程,不一定是主线程.
- 关键:指定仅在一个线程上的一个线程上执行代码时间.
- Single: Lets you specify that a section of code should be executed ona single thread, not necessarily the master thread.
- Critical: Specifies that code is only be executed on one thread at atime.
因此,这意味着在这两个代码中,之后的确切代码段将仅由一个线程执行,而其他线程将不会进入该段,例如如果我们打印一些东西,我们将在屏幕上看到一次结果,对吧?
So it means that in both, the exact section of code afterwards would be executed by just one thread and other threads will not enter that section e.g. if we print something, we will see the result on screen once, right?
差异如何?看起来很重要,要注意执行时间,但不是一个!但是在实践中我看不出任何差别!这是否意味着对其他线程(不进入该部分)的等待或同步被认为很重要,但是没有什么可以将其他线程保持为单个?在实践中如何改变结果?
How about the difference? It looks that critical take care of time of execution, but not single! But I don't see any difference in practice! Does it mean that a kind of waiting or synchronization for other threads (which do not enter that section) is considered in critical, but there is nothing that holds other threads in single? How it can change the outcome in practice?
我很高兴有人可以向我澄清这一点,特别是举个例子.谢谢!
I appreciate if anyone can clarify this to me especially by an example. Thanks!
推荐答案
single
和critical
是两个完全不同的事物.如您所述:
single
and critical
are two very different things. As you mentioned:
-
single
指定一段代码应由单线程(不一定是主线程)执行 -
critical
指定代码一次由一个线程执行
single
specifies that a section of code should be executed by single thread (not necessarily the master thread)critical
specifies that code is executed by one thread at a time
因此,前者将只执行一次 ,而后者将被执行与线程数量相同的次数.
So the former will be executed only once while the later will be executed as many times as there are of threads.
例如以下代码
int a=0, b=0;
#pragma omp parallel num_threads(4)
{
#pragma omp single
a++;
#pragma omp critical
b++;
}
printf("single: %d -- critical: %d\n", a, b);
将打印
single: 1 -- critical: 4
希望您现在能更好地看到区别.
I hope you see the difference better now.
出于完整性考虑,我可以添加:
For the sake of completeness, I can add that:
-
master
与single
非常相似,但有两个区别:
master
is very similar tosingle
with two differences:
-
master
仅由主机执行,而single
可以由先到达该区域的任何线程执行.和 -
single
在该区域完成时具有隐式屏障,该区域中所有线程都等待同步,而master
没有任何线程.
master
will be executed by the master only whilesingle
can be executed by whichever thread reaching the region first; andsingle
has an implicit barrier upon completion of the region, where all threads wait for synchronization, whilemaster
doesn't have any.
atomic
与critical
非常相似,但仅限于选择简单的操作.atomic
is very similar to critical
, but is restricted for a selection of simple operations.我添加了这些精度,因为这两对指令通常是人们容易混淆的...
I added these precisions since these two pairs of instructions are often the ones people tend to mix-up...
这篇关于ompcritical和omp single之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!