Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform basic operations with std::atomic when the type is not Integral?

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.

like image 972
Noozen Avatar asked Apr 16 '14 17:04

Noozen


People also ask

Is unsigned int Atomic?

Primitive types ( int , char etc) are not Atomic.

How do you declare an atomic variable in C++?

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.

Is STD atomic copyable?

std::atomic is neither copyable nor movable. The compatibility macro _Atomic is provided in <stdatomic.

What is std :: atomic used for?

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 .


1 Answers

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))
    ;
}
like image 128
Casey Avatar answered Oct 21 '22 13:10

Casey