How do you lock the Audio Thread?

I’ve never had a need to do this, and now that I want to try it, I can’t really find any examples of how to do it. Thanks!

If you’re using the AudioProcessor class take a look at the suspendProcessing method.

1 Like

suspendProcessing disables the callback. If you really want to lock, you should use getCallbackLock in a ScopedLock:

ScopedLock lock{ getCallbackLock() };

Of course this is usually a bad idea, but you know your case.

1 Like

It would be good to hear the use case to give proper advice (my 99% instinct is: just don’t!)

The ScopedLock works that way, that aquiring the lock on the same thread is a NOP.
getCallbackLock() returns the critical section, that the processBlock() call is locking, so you can stop processBlock() from happening by locking it from a different thread.

This leads to priority inversion, i.e. you high priority thread gets below the priority of the locking thread.

Thank you!!! It looks like suspendProcessing() does what I needed to do.

Yeah, it sounds like my idea of locking the Audio Thread was not really the right thing, I’m not sure I understand exactly what that does, I was just trying to figure out a way to deal with this:

I have a plugin that is a wrapper for another plugin. This is part of a plugin host based on AudioProcessorGraph, so the wrapped plugin (i.e. a synth instrument) can have processBlock() etc. intercepted by the wrapper and pre-processed before being sent to the wrapped plugin. You can replace the wrapped plugin inside the wrapper while the AudioProcessorGraph is running with a different synth instrument plugin selected from a PluginListComponent.

I mainly program on the Mac, and so this was all working fine. However, moving over to Windows, it would crash when replacing the wrapped plugin in realtime due to, apparently, ProcessBlock still being called while it’s being replaced. I don’t know why this works on the Mac, but in any case, it appears that suspendProcessing() is exactly what I needed; just wrapping the replacement in this apparently fixes it.

It seems like the right way to me. It’s a dirty operation any way you do it, but suspending will minimize the chance of priority inversion.

In our setup we have an AudioSource that receives intermittent inputs from a separate thread for some DSP heavy lifting. Our solution is to put a lock-free queue of AudioBuffer inside that AudioSource, and in the audio callback, return an empty buffer if the queue becomes empty. It sounds like this solution will also work in your application.

p.s. the lock-free queue implementation we’re using is https://moodycamel.com/blog/2013/a-fast-lock-free-queue-for-c++