difference between standard's atomic bool and atomic flag
std::atomic bool type not guranteed to be lock-free?
Correct. std::atomic
may be implemented using locks.
then it's not atomic or what?
std::atomic
is atomic whether it has been implemented using locks, or without. std::atomic_flag
is guaranteed to be implemented without using locks.
So what's the difference b/w two
The primary difference besides the lock-free guarantee is:
std::atomic_flag
does not provide load or store operations.
and when should I use which?
Usually, you will want to use std::atomic<bool>
when you need an atomic boolean variable. std::atomic_flag
is a low level structure that can be used to implement custom atomic structures.
std::atomic<T>
guarantees that accesses to the variable will be atomic. It however does not says how is the atomicity achieved. It can be using lock-free variable, or using a lock. The actual implementation depends on your target architecture and the type T
.
std::atomic_flag
on the other hand is guaranteed to be implemented using a lock-free technique.