Atomic Operations
Atomic operations are a fast and relatively easy alternative to mutexes. They do not suffer from the deadlock and convoying problems described earlier, in the section “Lock Pathologies.” The main limitation of atomic operations is that they are limited in current computer systems to fairly small data sizes: the largest is usually the size of the largest scalar, often a double-precision floating-point number.
Atomic operations are also limited to a small set of operations supported by the underlying hardware processor. But sophisticated algorithms can accomplish a lot with these operations; this section shows a couple of examples. You should not pass up an opportunity to use an atomic operation in place of mutual exclusion.
The class atomic<T>
implements atomic operations with C++ style.
A classic use of atomic operations is for thread-safe reference counting. Suppose x
is a reference count of type int
and the program needs to take some action when the reference count becomes zero. In single-threaded code, you could use a plain int
for x
, and write --x
; if(x==0) action()
. But this method might fail for multithreaded code because two tasks might interleave their operations, as shown in Figure 7-1, where ta
and tb
represent machine registers and time progresses downward.
Figure 7-1. Interleaving of machine instructions
The problem shown in Figure 7-1 is a classic race condition. ...
Get Intel Threading Building Blocks now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.