Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between standard's atomic bool and atomic flag

I wasn't aware of the std::atomic variables but was aware about the std::mutex (weird right!) provided by the standard; however one thing caught my eye: there are two seemingly-same (to me) atomic types provided by the standard, listed below:

  1. std::atomic<bool>

  2. std::atomic_flag

The std::atomic_flag contains the following explanation:

std::atomic_flag is an atomic boolean type. Unlike all specializations of std::atomic, it is guaranteed to be lock-free. Unlike std::atomic<bool>, std::atomic_flag does not provide load or store operations.

which I fail to understand. Is std::atomic<bool> not guaranteed to be lock-free? Then it's not atomic or what?

So what's the difference between the two and when should I use which?

like image 492
hg_git Avatar asked Sep 05 '16 11:09

hg_git


People also ask

What is an atomic flag?

std::atomic_flag is an atomic boolean type. Unlike all specializations of std::atomic, it is guaranteed to be lock-free. Unlike std::atomic<bool>, std::atomic_flag does not provide load or store operations.

Is std atomic bool lock-free?

atomic<bool>. std::atomic_flag i s the only atomic data type that is lock-free.

When to use atomic_ flag?

atomic_flag is a really low level construct which isn't meant to be widely used. That said, I believe you're usage works as you intend, except possibly clearing the flag in exceptional cases. If an exception other than one matched by std::exception occurs the flag does not get cleared.


2 Answers

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.

like image 152
eerorika Avatar answered Sep 19 '22 10:09

eerorika


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.

like image 27
michalsrb Avatar answered Sep 17 '22 10:09

michalsrb