Introduction
we see simple thread synchronization with Win32 API and MFC.
Background
Mutex:
A mutex object is a synchronization object whose state is set to signaled when it is not owned by any thread, and nonsignaled when it is owned.Only one thread at a time can own a mutex object, whose name comes from the fact that it is useful in coordinating mutually exclusive access to a shared resource. For example, to prevent two threads from writing to shared memory at the same time, each thread waits for ownership of a mutex object before executing the code that accesses the memory. After writing to the shared memory, the thread releases the mutex object.
Example1:
deadlock 1
void CMyClass::DoSomething()
{
HANDLE hMutex = ::CreateMutex( NULL, FALSE, lpszName );
::WaitForSingleObject(m_hMutex, INFINITE);
if( i == 0) return; else printf("foo");
ReleaseMutex(hMutex);
}
Example2:
deadlock 2
void CMyClass::DoSomething()
{
EnterCriticalSection(&m_cs)
if( i == 0) return; else printf("foo");
LeaveCriticalSection(&m_cs);
}
Using the code
avoid deadlock ( mutithread safe )
class CSimpleMutex {
public:
CSimpleMutex(LPCTSTR lpszName = NULL) : m_hMutex(NULL) {
m_hMutex = ::CreateMutex( NULL, FALSE, lpszName );
::WaitForSingleObject(m_hMutex, INFINITE);
}
virtual ~CSimpleMutex() {
if (m_hMutex) {
ReleaseMutex(m_hMutex);
}
}
protected:
HANDLE m_hMutex;
}
DoSomething0 and DoSomething1 are synchronized
void CMyClass::DoSomething0()
{
CSimpleMutex m("lock1");
if( foo == NULL) return;
return;
}
void CMyClass::DoSomething1()
{
CSimpleMutex m("lock1");
if( foo == NULL) return;
return;
}
void CMyClass::DoSomething2()
{
CSimpleMutex m("another lock");
if( foo == NULL) return;
return;
}
Conclusion
CSimpleMutex is very simple, Happy programming!