0

is_lock_free atomic_bool

Hi Came to know that atomic_bool is not lock free and hence we have spinlock. Refer code below (https://www.sololearn.com/en/compiler-playground/ciuT8ghwcf38): #include <iostream> #include <atomic> using namespace std; int main() { atomic<int> a(2); cout << a.is_lock_free() << endl; atomic<bool> b(false); cout << b.is_lock_free() << endl; return 0; } It shows b variable as lock free. Still spin lock is needed?

20th May 2025, 7:18 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Respostas
+ 1
std::atomic<bool>::is_lock_free() == true means atomic reads/writes are fast and don’t use a mutex. But atomic<bool> only protects itself, not a block of code. Spinlocks are still needed when you want to protect a critical section, not just a variable. So yes even if atomic<bool> is lock-free, spinlocks still have their use
27th May 2025, 10:48 PM
Ebrahim Hany
Ebrahim Hany - avatar
0
Do you mean atomic<bool> b; If(b)//b is atomic and works with threads fine { //critical section and not thread safe } ----‐------ If above is true (I belive it is) , then mutex is needed always. Right ? How spin lock is helping there without mutex ?
30th May 2025, 10:00 AM
Ketan Lalcheta
Ketan Lalcheta - avatar