In my earlier post Thread Synchronization in Windows using Critical Section, I have used Windows Critical Section as Locks for synchronizing the threads. This post talks about using Windows Mutex as synchronization objects and demonstrates it's use with a simple example. Windows functions related with Mutexes are CreateMutex, ReleaseMutex and OpenMutex
HANDLE CreateMutex( LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCTSTR lpName );
BOOL ReleaseMutex( HANDLE hMutex );
HANDLE WINAPI OpenMutex( DWORD dwDesiredAccess, BOOL bInheritHandle, LPCTSTR lpName );
Key Points
1. A thread acquires a mutex by calling WaitForSingleObject(HANDLE hMutex, DWORD dwMilliseconds);
2. A thread releases mutes by calling ReleaseMutex(HANDLE hMutex);
3. The WaitForSingleObject call returns when the specified object is in the signaled state or when the time out interval has lapsed
The MutexLock class implementation using Windows Mutex synchronization Object
#ifndef _MutexLock_H_ #define _MutexLock_H_ //File: MutexLock.h #include <windows.h> #include <process.h> #include <iostream> #include "NonCopyable.h" namespace examples { class MutexLock : public NonCopyable { public: MutexLock() { m_hMutex = (HANDLE) ::CreateMutex(0, 0, 0); if(NULL == m_hMutex) { std::cout << "ERROR: Cannot create mutex" << std::endl; } } ~MutexLock() { ::CloseHandle(m_hMutex); } void acquire() { if(::WaitForSingleObject(m_hMutex, INFINITE) != WAIT_OBJECT_0) { std::cout << "ERROR: Cannot acquire mutex" << std::endl; } } bool tryAcquire(size_t timeOut) { bool retval = false; switch(::WaitForSingleObject(m_hMutex, timeOut)) { case WAIT_OBJECT_0: retval = true; break; case WAIT_TIMEOUT: std::cout << "ERROR: Cannot acquire mutex" << std::endl; break; default: std::cout << "ERROR: Cannot acquire mutex" << std::endl; break; } return retval; } void release() { if(::ReleaseMutex(m_hMutex) == 0) { std::cout << "ERROR: Cannot release mutex" << std::endl; } } private: HANDLE m_hMutex; }; } #endif //_MutexLock_H_
Read more ...