Launching task in another thread from realtime thread

I would really like to do the following:

AudioAppComponent::getNextAudioBlock() plays data it receives from outside systems. When the buffered data is running low, getNextAudioBlock() requests more data. In my case the best way to do that is to either send a message from this realtime thread or to activate an extra thread that handles the new data processing and sending to getNextAudioBlock() routine.

What is the most responsive way to do the above? Only one such message or thread activation is required about once per second. Let’s say I have 32 samples long audio buffers, so whatever way the external source gets activated with, it shouldn’t stall the realtime thread for such a long time that those 32 samples get played already and I hear snap crackle pop my loud speakers.
The data itself will be requested well in advance, maybe 1 second before it’s actually required.

I currently have a timer which polls everything required at about 20 Hz frequency, but I find it creates more issues than it solves. Because of this I’m convinced I should use another approach, i.e. one I’m asking about. “On demand system” is the preferred way in my case instead of polling.

Any insights and experiences on this?

Reading documentation I notice there’s also MessageManager::callAsync(). Would that also do the trick? How heavy that method is to activate, so that I know if it’s feasible to call that from the realtime thread. I cold embed the request audio block information into that lambda function the callAsync() forwards to the message thread.

Still the best method for me would be to send an actual message with couple of bytes of extra data in it to describe time stamps for the requested incoming audio data and to be able to implement X amount of audio sources that can operate independently from each other in their own threads if need be. This would future proof my design in a nice way.

1 Like

The method callAsync allocates and blocks the message thread if not called from it. Just stick a separate thread around and communicate with a pair of lock free queues.

2 Likes

I already tried using callAsync. Seems to work, for now. If problems arise, I’ll try your suggestion about using a dedicated thread.

Thanks!

This “for now” describes the problem perfectly. As long as the threads never interfere (and the OS doesn’t get stuck on the system call) everything is fine. But then the like 0.1% odds kick in and one of your audio blocks lags.
I’d advise to do such stuff early in the project while it is still easy. :wink: