Hi there,
My current project involves having several worker threads running a simulation loop as fast as possible, with the main thread displaying the current state once per frame. The frequency of the worker threads is much higher than the main thread's render.
I'm currently using Windows threads, but I've tried the equivalent in pThread, and I get the same results.
My plan is to have the worker threads at a lower priority than the main thread. Each sim loop they lock a mutex, do the sim, unlock the mutex and sleep(0).
When the higher priority main thread wants to render one of the worker threads, it locks the mutex, does the render then unlocks the mutex.
What I *think* should happen is that as soon as the main thread wants to render, it will wait for the mutex. As soon as one of the worker threads finishes the sim, it unlocks the mutex and sleeps, which should yield to any higher priority thread. So, the render should be nice and responsive.
Here's some code snippets to help clarify:
Thread creation:
mSimMutex = CreateMutex(NULL, false, NULL);
mThread = CreateThread(
NULL,
0,
ThreadProc,
this,
CREATE_SUSPENDED,
NULL);
SetThreadPriority(mThread, THREAD_PRIORITY_BELOW_NORMAL);
ResumeThread(mThread);
Thread loop:
DWORD WINAPI SimThread::ThreadProc(void* lpThis)
{
float lfElapsed = 0.0f;
float lfTimeStep = 1.0f/60.0f;
SimThread* lpSim = (SimThread*)lpThis;
while (lfElapsed < 100.0f)
{
WaitForSingleObject(lpSim->mSimMutex, INFINITE);
lpSim->Step(lfTimeStep);
lfElapsed += lfTimeStep;
ReleaseMutex(lpSim->mSimMutex);
Sleep(0);
}
return 0;
}
Main thread render function:
void SimThread::Draw()
{
WaitForSingleObject(mSimMutex, INFINITE);
ReleaseMutex(mSimMutex);
}
What actually happens is that the draw method blocks for a large amount of time (until the worker thread actually finishes). It looks like the main thread never takes advantage of the Sleep() on the worker thread - the worker thread just carries straight on and re-grabs the mutex.
I'm not massively experienced with threading, so I'm at a bit of a loss as to what's going on. If anyone can suggest anything I'd be hugely grateful.
Thanks,
Rob.
P.S. In case it's relevant, I'm coding in Eclipse, using MinGW/GCC toolchain, under Windows 7.