To be precise, I only need to increase a double by another double and want it to be thread safe. I don't want to use mutex for that since the execution speed would dramatically decrease.
Primitive types ( int , char etc) are not Atomic.
In order to solve this problem, C++ offers atomic variables that are thread-safe. The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.
std::atomic is neither copyable nor movable. The compatibility macro _Atomic is provided in <stdatomic.
Module std::sync::atomic. Atomic types provide primitive shared-memory communication between threads, and are the building blocks of other concurrent types. Rust atomics currently follow the same rules as C++20 atomics, specifically atomic_ref .
As a rule, the C++ standard library tries to provide only operations that can be implemented efficiently. For std::atomic
, that means operations that can be performed lock-free in an instruction or two on "common" architectures. "Common" architectures have atomic fetch-and-add instructions for integers, but not for floating point types.
If you want to implement math operations for atomic floating point types, you'll have to do so yourself with a CAS (compare and swap) loop (Live at Coliru):
std::atomic<double> foo{0};
void add_to_foo(double bar) {
auto current = foo.load();
while (!foo.compare_exchange_weak(current, current + bar))
;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With