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
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