📄 34.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <style type="text/css"> body { font-family: Verdana, Arial, Helvetica, sans-serif;} a.at-term { font-style: italic; } </style> <title>The Critical Section</title> <meta name="Generator" content="ATutor"> <meta name="Keywords" content=""></head><body> <p>The critical directive ensures that the immediately following block of code is executed by only one thread at a time in a parallel region. The first thread to arrive at the critical section proceeds to enter; threads that arrive subsequently wait until the thread currently inside it has exited. </p>
<p class="codelang">Fortran syntax:</p>
<pre><code>!$omp critical [(name)]
<em>structured block of code</em>
!$omp end critical</code></pre>
<p class="codelang">C/C++ syntax:</p>
<pre><code>#pragma omp critical [(name)]
<em>structured block of code</em></code></pre>
<p>The directive takes an optional name argument, which identifies the critical section. <em><a href="../glossary.html#critical+section" target="body" class="at-term">Critical section</a>s</em> are independent of one another unless they have the same name. For critical sections with different names, there is no prohibition against having one thread active in each of them at the same time. All unnamed critical sections are considered to have the same identity. </p>
<p>The following example illustrates the use of critical sections: </p>
<pre><code>integer cnt1, cnt2
c$omp parallel private(i)
c$omp& shared(cnt1,cnt2)
c$omp do
do i = 1, n
...<em>do work</em>...
if (condition1) then
c$omp critical (name1)
cnt1 = cnt1+1
c$omp end critical (name1)
else
c$omp critical (name1)
cnt1 = cnt1-1
c$omp end critical (name1)
endif
if (condition2) then
c$omp critical (name2)
cnt2 =cnt2+1
c$omp end critical (name2)
endif
enddo
c$omp end parallel</code></pre>
<p>Note that there are two separate critical sections, name1 and name2. The two critical directives associated with name1 ensure that cnt1 will be updated correctly
whether it is being incremented or decremented; only one thread is allowed to execute either of these statements at any given time. The critical section name2 is independent, however; only one thread may update the value of cnt2 at any given time, but there is no reason that another thread could not simultaneously update cnt1. </p></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -