The C++ standard library
In multithreaded programming, data synchronization and thread safety are important issues.
The C++11 standard introduced library, which provides a set of atomic operations to guarantee that access to a single piece of data in a multithreaded environment is atomic, i.e., indivisible. This avoids data races and ensures thread safety.
An atomic operation is one that cannot be interrupted by other threads during its execution.
The atomic types in the library provide such operations; they guarantee that access to shared data in a multithreaded environment is safe.
Syntax
The library provides various atomic types, includingatomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, atomic, etc.
Basic operations
load(): Safely reads the value of an atomic variable.store(value): Safely writes a value to an atomic variable.exchange(value): Replaces the value of the atomic variable withvalue, and returns the old value of the atomic variable.compare_exchange_weak(expected, desired): If the current value of the atomic variable equalsexpected, sets it todesired, and returnstrue. Otherwise, setsexpectedto the current value of the atomic variable, and returnsfalse.compare_exchange_strong(expected, desired): Similar tocompare_exchange_weak, but loops until success.
Example
Below is an example usingis a simple example of the library, demonstrating how to safely update a shared counter in a multithreaded environment.
Example
#include
#include
#include
std
::
atomic
<
int
counter
(
0
);
// Initialize atomic counter
void
increment
(
)
{
for
(
int
i
=
0
;
i
<
10000
;
++
i
)
{
counter.
fetch_add
(
1
, std
::
memory_order_relaxed
)
;
// Atomic increment
}
}
int
main
(
)
{
std
::
thread
t1
(
increment
)
;
std
::
thread
t2
(
increment
)
;
t1.
join
(
)
;
t2.
join
(
)
;
std
::
cout
<<
"Final counter value: "
<<
counter
<<
std
::
endl
;
// Output the final counter value
return
0
;
}
Running the program above, you will see output similar to:
Final counter value: 20000
This output indicates that two threads successfully incremented the counter 10000 times each without data races.
Notes
- Use
library, you need to ensure that all access to shared data is done through atomic operations, to avoid data races. - Different atomic operations have different memory ordering requirements;
std::memory_order_relaxedis the lowest memory ordering requirement, but may not guarantee operation visibility. Choose the appropriate memory order as needed. - Atomic operations usually have higher performance overhead than non-atomic operations, so in a single-threaded environment, using ordinary variables may be more efficient.
By usinglibrary, C++ programmers can more easily write thread-safe code while maintaining high performance.