Proper usage of Thread for running various tasks

I’m starting to get the hang of JUCE and C++ after spending some time with it over the last few weeks and I’m really enjoying it but still struggling a bit on threading and resource management.

I have a plugin where the user can load audio files for playback for various reasons. Part of that process is doing sample rate conversion. When I had this running on the main thread, it caused a short freeze in the DAW, understandably.

What I did is create a Thread called backgroundThread… but I never actually start that thread. Instead I’m using backgroundThread.launch with the lambda function that does the sample rate conversion.

This works perfectly, seems much quicker (the conversion happens immediately), and doesn’t cause the short freeze in the DAW. Is this a reasonable way to go about this? If not, what should I be doing instead?

The reason I ask is because there are bound to be other processor intensive functions (not related to realtime playback) I plan to call that probably shouldn’t be on the main thread and since this seems to work, I would probably continue doing it this way unless

a) there is a better way to do it
and/or
b) there are drawbacks.

Thanks in advance - appreciate everyone’s expertise!

A ThreadPool is a good way of managing tasks that should be done on a background thread. You can assign a new job as a lambda function. It’s also straightforward to manage threads this way.

1 Like

If you are calling it from your audio thread, careful with the lock inside ThreadPool::addJob().
In practice this is rarely a problem if you aren’t adding lots of jobs at once but for a lock free version of threadPool take a look here: Lock free thread pool

1 Like

Thanks guys! I have the thread pool working but I’ll look at incorporating that lock free thread pool code