Click to See Complete Forum and Search --> : Synchronization with mutex problem, please help!


daoanhvu
July 11th, 2011, 07:17 AM
Hi All,

I use a mutex to synchronize device context between threads.

I create mutex from the main thread as follow:

g_displayMutex = CreateMutex(NULL, FALSE, L"DiplayMutex");


The thread's routine is defined as follow:

DWORD WINAPI StartMoving(void *param)
{
CMyBall *p = (CMyBall*)param;
DWORD flag = 0;
while(p->Alive())
{
flag = WaitForSingleObject(g_displayMutex, 100);

switch(flag)
{
case WAIT_OBJECT_0:
p->move();
p->draw(g_memDC);
InvalidateRect(g_hWnd, NULL, true);
UpdateWindow(g_hWnd);

ReleaseMutex(g_displayMutex);
Sleep(20);
break;

case WAIT_ABANDONED:
p->SetAlive(FALSE);
return 1;
}
}

return 0;
}


When user close the program, I wait for the mutex and set the living status of object to false:

case WM_DESTROY:

if(WaitForSingleObject(g_displayMutex, INFINITE) != WAIT_OBJECT_0)
{
MessageBox(NULL, L"Wait fail", L"WM_DESTROY", MB_OK);
}

for(int i=0; i<gNumOfBall; i++)
gBalls[i].SetAlive(FALSE);
ReleaseMutex(g_displayMutex);

WaitForMultipleObjects(gNumOfBall, gThreads, TRUE, INFINITE);

for(int i=0;i<gNumOfBall;i++)
{
CloseHandle(gThreads[i]);
}

CloseHandle(g_displayMutex);

//Release memory DC here
ReleaseMemoryDC(hWnd);
...
PostQuitMessage(0);
break;

The problem is the process does not end when the program closed. I have to press "Stop Debug" from VS (I use VS2010) to force it stop.

Please friends, help me on this problem, many thanks in advance!
Nautilus

Arjay
July 13th, 2011, 02:01 PM
You can create an exit event and use WaitForMultipleObjects in your thread to wait on the mutex and the exit event. When you want to exit the program, call SetEvent on the exit event (which will force the threads to exit).

Btw, SetAlive doesn't appear to be thread safe. If you are using a BOOL parameter, it's actually an int which doesn't get set atomically.