Thread question: one-shot or query running thread?

I have a design question regarding the best way to use a thread to handle an occasional request from the Processor.

I have a need to sometimes perform an analysis of some audio that I’ve recorded from the processBlock() function, and I want to do this analysis on a background thread, and report back when that analysis has completed and certain data has been generated that the Processor can consume.

Would it be better to spawn this thread at startup, and let it run continuously, and then asking it, when needed, to perform this task, OR, would it be better to spawn it only when needed, and terminate it after posting its data and flagging the Processor that it is done?

I’m not worried about spawning it during processing; that is done when the user clicks a button to start the Analysis processing, and then the processBlock() function simply uses its current data until it has, at some point, consumed the data and is ready to process using that new data.

My concern is more about whether having that extra thread running at all times consumes resources that would be better used by other processes unless and until the user has asked for this Analysis phase to begin. Or whether it’s better, in general, to leave a background thread running and simply wake it up when needed to perform this task (which may take anywhere from a fraction of a second to a couple of seconds, and which will likely only be run once or twice in a particular session).

One consideration: multiple instances of a plugin can exist, so if every instance spawns an extra thread, will that limit the number of instances that can be opened? (I don’t want to use a shared singleton, because it’s possible that multiple instances could all be in this Analysis mode at once, and I don’t want one instance to wait on others. That could lead to unacceptable delays.)

create a thread each time if this is something that you run once or twice in a particular session

That was my thought, too. Normally I prefer to keep resources available to avoid the overhead of creating/destroying them every time they are needed, but in this case, I think not having the thread always running might be better. That’s what I’ve done.

That’s true, if the thread is actively doing something. But you can use a WaitableEvent and wake the thread up only when you want work to be done.