Simple Audio/GUI Thread Safety Question

Hi all,

My PluginProcessor has a member double, which is periodically read by the PluginEditor to update a graphic component. PluginProcessor always writes, and PluginEditor always reads. Do I need to use atomic or mutex for thread safety, or is this always OK?

I’ve been going through the forum reading about thread-safety and haven’t been able to draw a definitive conclusion.

Thanks,

Using an atomic double would be recommended.

3 Likes

One some platforms a double is NOT atomic, that is - it can get sliced in half when crossing threads.
Using atomic double is always safe.

1 Like

TLDR: Use std::atomic<double>. NEVER use a mutex (lock) on any code that the audio thread can run.

More info: Thread safety and lock-free concurrent programming in Juce is something I always struggle with. Timur (an ex-Roli employee) gave some great ADC presentations on the topic. This one specifically covers floating atomics.

The timestamp starts at an example where he states that writing/reading a float (32 bit) with the message/audio threads is a race condition. He goes on to admit that float read/writes are atomic on pretty much any architecture that would run a plugin, but apparently the compiler could misinterpret the intent and mess with things. So he even recommends using std::atomic for floats (although I’ve certainly made plugins without and had no issues). Regarding doubles, standard read/writes on a double might not be atomic depending on the build.

I also recommend the first part of that series, found here:

2 Likes