Question about atomics

Just a quick question.

I recently watched one of the conferences about using std::atomic in the processBlock/Audio thread.

Should I always be using std::atomic when storing/loading and variables that will be accessed in the processBlock and outside of the processBlock function ? I wasn’t previously, so I’m guessing its not dire, but good practice.

A basic example being, I have a variable for the RMS level that I need to access from other threads at points. So this should be an std::atomic right?

And is storing/loading an atomic expensive? Especially considering its being done ~100 times a second?

Thanks.

Yes you should be using atomics. The issue you are avoiding is one thread might be writing new data to memory as another thread is reading it, so what ends up being read is some half/half value that results in undefined behaviour.

Apparently on some architectures floats behave like an atomic anyway, so that could be why you never had an issue with the RMS value. But it might be an issue on another system, so you should just avoid data races entirely.

1 Like

HTH:

You could use memory_order_relaxed to minimize the cost, but you need to fully understand it.

If not, just use default std::atomic and think about optimization later.

1 Like

Should I always be using std::atomic when storing/loading and variables that will be accessed in the processBlock and outside of the processBlock function ? I wasn’t previously, so I’m guessing its not dire, but good practice.

You don’t need to use atomics for everything that’s used in and out of the process block, only things that are used on multiple threads.

Also, there’s some cases where it’s safe to use things on multiple threads without atomics or other thread safety. For example prepareToPlay, releaseResources, and numChannelsChanged (IIRC) will likely be called on the main thread, but the audio thread won’t be running at that point so it’s safe to use things that will also be used on the audio thread.

A basic example being, I have a variable for the RMS level that I need to access from other threads at points. So this should be an std::atomic right?

That sounds like a good use-case for an atomic, yeah!

2 Likes