I'm writing a realtime audio multithreaded application, and during the render cycle sometimes there will be no jobs on the work queue. I would like the thread to wait for jobs without triggering an OS context switch (which could be too damaging to performance), yet also "efficiently" in the sense that we probably don't need to be burning at 100% of the processor's capacity. I'm not quite sure what that means, but apparently Windows has a WaitForProcessor()
function which indicates we are spinlocking and it can use a bit of the processor for hyperthreads, so it made me think that there could be a best practice here. It is a cross-platform application.
If there is no portable solution, I'm interested in platform-specific information for Windows, MacOS, Android, and iOS.
Currently it looks essentially like this:
// Variables shared between threads:
std::atomic<bool> done;
LockFreeFIFO<Job> workQueue;
// Thread process loop:
while (!done.load()) {
Job job;
if (workQueue.remove(&job)) {
job.run();
}
else {
// "semi-yield"? What goes here?
}
}