I am trying to learn how to use atomic :)
class foo {
static std::atomic<uint32_t> count_;
uint32 increase_and_get() {
uint32 t = count_++;
return t;
}
}
Is the function increase_and_get()
thread-safe?
Atomic classes allow us to perform atomic operations, which are thread-safe, without using synchronization. An atomic operation is executed in one single machine-level operation.
So atomic operations on primitive data types are a tool to achive thread safety but do not ensure thread safety automatically because you normally have multiple operations that rely on each other. You have to ensure that these operations are done without interruption eg using Mutexes.
Thread safety A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface. The use of global data is thread-unsafe.
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.
Yes, it is safe: the increment is atomic, and the local t
cannot be altered by concurrent threads. You can further simplify your code to eliminate the temporary variable altogether:
uint32 increase_and_get() {
return count_++;
}
Yes, it would be threadsafe. Assuming of course there are no bugs in the std::atomic
implementation - but it's not usually hard to get right.
This is exactly what std::atomic
is meant to do.
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