Reason for ScopedLock in JuceDemo - AudioLatencyDemo.cpp


What’s the reason for using a ScopedLock in the audioDeviceIOCallback in the LatencyTester class in the AudioLatencyDemo.cpp in the JuceDemo? Because you often read in the forum that you should not use locks in the audio thread. What is special here?

void audioDeviceIOCallback (const float** inputChannelData,
                                int numInputChannels,
                                float** outputChannelData,
                                int numOutputChannels,
                                int numSamples)
        const ScopedLock sl (lock);

        if (testIsRunning)
            float* const recordingBuffer = recordedSound.getWritePointer (0);
            const float* const playBuffer = testSound.getReadPointer (0);


“Should not” does not mean “everybody is always going to do a fancy
overcomplicated lock free solution for everything”, especially if it’s just some demo/example code.


Yeah, in that example we don’t care if it glitches.

But also note that a completely uncontended lock is real time safe. Obviously a lock that is never taken by any other thread is pointless, but if you know that the lock will only ever be contended at a time when you don’t care what happens (e.g. the app has already stopped playing and is shutting down, or it’s starting up and not yet playing) then it’s harmless. But this is a subtle point, so we prefer the message to be “never use locks”! :slight_smile:


Thank you for the quick response! What is critical in that code that it is locked here? Is it the recordedSound AudioBuffer?
Because I am implementing something similar where an audio signal is recorded and analysed later.