Priority inversion in AudioRecorderDemo?

I haven’t faced any problem in AudioRecorderDemo yet, but if I understand things correctly, it will cause priority inversion to lock audio thread.

Or, is there any reason not to use try lock but CriticalSection in this case?

The demos and examples are just that, demos and examples, not guides on how to write 100% correct production code. (It’s worth noting though, that the Juce library code itself also uses CriticalSections and SpinLocks in various places where they are going to lock the audio thread.)

Ah, sorry, I research the code and found a little mistake.
So please forgive to change the question.
The Criticalsection writerLock seems to protect activeWriter, which is atomic pointer to the ThreadedWriter. Is the writerLock necessary? std::atomic is not enough for the thread safety?

Additionally to Xenakios’ answer it’s worth pointing out:

The lock avoids the writer being set or unset while it is being used. The code they are guarding is as fast as it could be, so the danger is minimal (even though you are correct, in extreme cases it could glitch).

The situations when the lock is acquired on the low priority thread is, when the user starts or stops recording. Many demos (and even products) work on the premise, if the user twiddles a knob a short glitch can be excused.

A std::atomic for a complex type would possibly end up with the same code…

Thank you for you two to make things clearer.
And I’m relief that I’m not totally wrong.

One thing I want to ask is

A std::atomic for a complex type would possibly end up with the same code…

What does it mean?Do you mean, there is platforms a pointer may not be is_always_lock_free?

Yes, that was not thought through by myself. But atomic has another problem. It won’t protect the callback from the pointer being removed while writing.

Oh, I got it. You mean, the problem is about what the pointer points to. When it was destructed, there is no guarantee for the atomic to protect what it points to. It only protects pointer object itself. That is why we need lock. Am I right?
If so, that’s really important!
Thank you very much for pointing it!