Loop without consuming too many CPU cycles and without sleep()? Loop without consuming too many CPU cycles and without sleep()? multithreading multithreading

Loop without consuming too many CPU cycles and without sleep()?


The best thing to do, if you can, is to not emulate an event-driven architecture as you say, but to actually use an event-driven architecture. I don't know anything about your code, in particular whether you're in control of the audio-recording buffer's code or not. But if you do control the code that writes to the buffer, then you can trigger an event when you have written to the buffer:

(psudocude follows)

Main Thread:

HANDLE buf_event = CreateEvent(...);// ...CreateThread(BufferControl, ...);

Buffer-Write Thread:

OnWriteToBuffer(){  buffer.Write(...);  SetEvent(buf_event);}

And then in the thread where you want to do something when there's data in the buffer waiting, wait for the event to be signaled:

Buffer-Read Thread

rc = WaitForSingleObject(buf_event, INFINITE);if( rc == WAIT_OBJECT_0 ){  // there's somethign in the buffer}


You could use 'SwitchToThread' to yield the processor to another thread, and check the return value. If it is true, you yielded, and if not, there are no other threads that need running. If I remember correctly, FMOD runs a thread, so you would likely be yielding to that thread.

If it fails to yield or if it continues to use up a lot of CPU time, you could use some combination of yielding and sleeping.


I'm not familiar with the FMOD library, but does it provide a notification callback for when data is placed in the buffer? If not, you're pretty much stuck using some form of sleep (you could put that code in a thread and use something like nanosleep to still have good response times though).