mirror of
https://github.com/OpenMP/Examples.git
synced 2025-04-08 07:32:12 +01:00
59 lines
2.6 KiB
TeX
59 lines
2.6 KiB
TeX
%\pagebreak
|
|
\section{\kcode{atomic} Construct}
|
|
\label{sec:atomic}
|
|
\index{constructs!atomic@\kcode{atomic}}
|
|
\index{atomic construct@\kcode{atomic} construct}
|
|
\index{atomic construct@\kcode{atomic} construct!update clause@\kcode{update} clause}
|
|
\index{clauses!update@\kcode{update}}
|
|
\index{update clause@\kcode{update} clause}
|
|
|
|
The following example avoids race conditions (simultaneous updates of an element
|
|
of \ucode{x} by multiple threads) by using the \kcode{atomic} construct .
|
|
|
|
The advantage of using the \kcode{atomic} construct in this example is that it
|
|
allows updates of two different elements of \ucode{x} to occur in parallel. If
|
|
a \kcode{critical} construct were used instead, then all updates to elements of
|
|
\ucode{x} would be executed serially (though not in any guaranteed order).
|
|
|
|
Note that the \kcode{atomic} directive applies only to the statement immediately
|
|
following it. As a result, elements of \ucode{y} are not updated atomically in
|
|
this example.
|
|
|
|
\cexample[3.1]{atomic}{1}
|
|
|
|
\fexample[3.1]{atomic}{1}
|
|
|
|
\index{atomic construct@\kcode{atomic} construct!write clause@\kcode{write} clause}
|
|
\index{atomic construct@\kcode{atomic} construct!read clause@\kcode{read} clause}
|
|
\index{write clause@\kcode{write} clause}
|
|
\index{clauses!write@\kcode{write}}
|
|
\index{read clause@\kcode{read} clause}
|
|
\index{clauses!read@\kcode{read}}
|
|
The following example illustrates the \kcode{read} and \kcode{write} clauses
|
|
for the \kcode{atomic} directive. These clauses ensure that the given variable
|
|
is read or written, respectively, as a whole. Otherwise, some other thread might
|
|
read or write part of the variable while the current thread was reading or writing
|
|
another part of the variable. Note that most hardware provides atomic reads and
|
|
writes for some set of properly aligned variables of specific sizes, but not necessarily
|
|
for all the variable types supported by the OpenMP API.
|
|
|
|
\cexample[3.1]{atomic}{2}
|
|
|
|
\fexample[3.1]{atomic}{2}
|
|
|
|
\index{atomic construct@\kcode{atomic} construct!capture clause@\kcode{capture} clause}
|
|
\index{capture clause@\kcode{capture} clause}
|
|
\index{clauses!capture@\kcode{capture}}
|
|
The following example illustrates the \kcode{capture} clause for the \kcode{atomic}
|
|
directive. In this case the value of a variable is captured, and then the variable
|
|
is incremented. These operations occur atomically. This example could
|
|
be implemented using the \emph{fetch-and-add} instruction available on many kinds of hardware.
|
|
The example also shows a way to implement a spin lock using the \kcode{capture}
|
|
and \kcode{read} clauses.
|
|
|
|
\cexample[3.1]{atomic}{3}
|
|
|
|
\fexample[3.1]{atomic}{3}
|
|
|
|
|