Thanks for all who helped with my last threads question. The CPU usage is now down to where it should be.
Next problem is terminating the threads. My system thus far works, but it is slow.
Each thread continues the loop, sleep, update, loop system as long as m_bActive is true and m_bVisible is true.
To terminate the thread I added an m_bThreadTerminated boolean and when the CAnimSequenceContainer destructor is called it iterates through all of the animation sequences and sets the m_bActive member to false. Then it loops until m_bThreadTerminated is true. m_bThreadTerminated is set to true when the thread loop exits due to m_bActive being false. It works and there are no leaks, but shutdown is a bit slow.
Is there any ways to exit quicker using threads while ensuring they shut down properly prior to the main process exiting?
Inside of CAnimSequence
Code:
static UINT DoThreading(LPVOID p)
{
CAnimSequence *ptrSeq=(CAnimSequence *)p;
while (ptrSeq->m_bActive)
{
if (ptrSeq->m_pWindow!=NULL)
{
if (ptrSeq->m_bVisible)
{
ptrSeq->m_fCurTime=(float)::timeGetTime();
float fElapsed=ptrSeq->m_fCurTime-ptrSeq->m_fLastTime;
float fPause=ptrSeq->GetCurFrameDuration();
::Sleep(ptrSeq->GetCurFrameDuration()*.10f);
ptrSeq->Update(fElapsed);
ptrSeq->m_fLastTime=ptrSeq->m_fCurTime;
}
}
}
ptrSeq->m_bThreadTerminated=true;
return (0);
}
Inside of CAnimSequenceContainer
Code:
virtual ~CAnimSequenceContainer(void)
{
//Terminate threads
for (DWORD i=0;i<AnimSeqs.size();i++)
{
AnimSeqs[i]->m_bActive=false;
while (AnimSeqs[i]->m_bThreadTerminated==false)
{
//Wait for thread to terminate
}
if (AnimSeqs[i])
{
delete AnimSeqs[i];
}
}
AnimSeqs.clear();
}