MultiThreaded audio processing strategy?


#1

Is this a good strategy?
In my app the audio thread calls back audioDeviceIOCallback as you would expect…
I also have 4 threads running and a conditional variable to signal when to do some work.
I pass through the reference to the output buffer to each thread and trigger them.

Back in the audio thread I wait until each is completed before further processing. Will this approach work well with Juce?

I do need the extra horsepower to make what I’m doing a realtime process and it can’t be done realtime on a single thread. I have benchmarked my operation and it only takes 23% of time of the buffer window with 4 threads but I get dropouts if I just do all the processing on the audio thread…

    void processCommandLoop()
    {
        while(running)
        {
            if(numCommands<=0) {
                std::unique_lock<std::mutex> lk(threadMtx);
                cv.wait(lk);
            }
            while(numCommands>0)
            {
                cmdMtx.lock();
                int cmd = commandQueue[0];
                FilterContext obj = commandQueueObject[0];
                commandQueue.erase(commandQueue.begin());
                commandQueueObject.erase(commandQueueObject.begin());
                commandQueue.shrink_to_fit();
                commandQueueObject.shrink_to_fit();
                cmdMtx.unlock();
                
                processCommand(cmd,obj);
                numCommands--;
                
                // If there are multiple commands then this gives other threads
                // a chance to run in the same priority group

                if(numCommands==0) {
                    finishedCV.notify_one();
                }
                
                std::this_thread::yield();
            }
        }

        //isJoined = true;
    }