Let’s say I have a USB device that gives me an int (gain) parameter based on sensor data. I have a listener class that receives this data 100 times a second. I want to update my processor gain based on this parameter. Is the only best way to do so using an atomic int? How can I avoid using atomic variables in general? Can I set the value on a callback function that runs synchronously on the audio thread?
In addition, let’s say I wanted to get this parameter from the processor to the plugin editor and display it to the screen. Would this be thread safe assuming a non-atomic int?
If you look into the JUCE code, you’ll see the way they handle parameters is by wrapping an atomic. Generally, you can use atomics, or lock-free queues. For this use case I’d assume using atomics is the best way to go, everything else would be overly complex for a gain value. Queues start to make more sense once you either have complex data structures, or a requirement to not just have the latest value, but a history of all values between polls. I have read that many primitive types act as atomics even when not declared as such, depending on the hardware. I’ve not confirmed this for myself, but for readability it’s probably best you explicitly declare things as atomics if it’s your intention. Just mentioning that in case you use a non atomic int and still detect no data race.
You can ‘set’ it from another thread and it will interpolate smoothly to your desired value when you read it on another; It solves the t̶h̶e̶ ̶t̶h̶r̶e̶a̶d̶i̶n̶g̶ ̶i̶s̶s̶u̶e̶ ̶a̶n̶d̶ ̶g̶l̶i̶t̶c̶h̶i̶n̶g̶/̶popping issues.
EDIT: Sorry! I was wrong about it being thread-safe, I thought we used atomics in SmoothedValue!