Can I share std::atomic among different threads?

there is said (I read somewhere) that if I have separate Thread, then other thread can’t use (or manipulate) variables which are used in Thread::run().

I want to ask if that’s the true for std::atomic? Can I use std::atomic to ensure run() method has always ready to use variable? And then can I use that std::atomic in other thread?

Yep! It allows data to be accessed safely from multiple, concurrent threads

1 Like


1 Like

But you have to be extremely careful in how you actually use the atomics.

1 Like

What do you mean in that case?

Also in other cases I always don’t understand what does mean all those “extremely careful”, “not allowed”, “strictly prohibited” etc. I am asking seriously. I am quite new in programming, and for me everything that can’t physically destroy my (or my client) computer is OK. Sorry if I am stupid, I just don’t understand it.

If you actually want your code to be correct and not leak memory or end up producing corrupted results and so on, you should understand all the warnings and caveats people often mention.

Using atomics is so difficult to get right, that I’ve hardly ever used them for anything beyond some very simple flag variables. (And even then the atomics have been used in the code mostly to prevent the compiler from optimizing the variables away. For example bools are atomic on many platforms even without wrapping them into std::atomic or Juce Atomic but the compiler may end up removing accesses to plain bool variables in release builds which leads to incorrect results.)

I also just want to use as a flag std::atomic<bool> so hopefully I don’t do anything “danger”.

It obviously depends on the exact code involved, but using


should not be too difficult to get right.

If you use an atomic flag instead

then lock-free behaviour is guaranteed.


Coding mistakes in audio can very easily create noises that can physically damage your gear and/or your ears… just saying…