Can I share std::atomic among different threads?


#1

Hello,
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?


#2

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


#3

Thanks!!


#4

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


#5

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.


#6

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.)


#7

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


#8

It obviously depends on the exact code involved, but using

std::atomic<bool> 

should not be too difficult to get right.


#9

If you use an atomic flag instead

https://en.cppreference.com/w/cpp/atomic/atomic_flag

then lock-free behaviour is guaranteed.


#10

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