July 11th, 2011, 08:17 AM
Synchronization with mutex problem, please help!
I use a mutex to synchronize device context between threads.
I create mutex from the main thread as follow:
The thread's routine is defined as follow:
g_displayMutex = CreateMutex(NULL, FALSE, L"DiplayMutex");
When user close the program, I wait for the mutex and set the living status of object to false:
DWORD WINAPI StartMoving(void *param)
CMyBall *p = (CMyBall*)param;
DWORD flag = 0;
flag = WaitForSingleObject(g_displayMutex, 100);
InvalidateRect(g_hWnd, NULL, true);
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.
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++)
WaitForMultipleObjects(gNumOfBall, gThreads, TRUE, INFINITE);
//Release memory DC here
Please friends, help me on this problem, many thanks in advance!
July 13th, 2011, 03:01 PM
Re: Synchronization with mutex problem, please help!
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.
Click Here to Expand Forum to Full Width
This is a Codeguru.com survey!