CMutexClassクラス
CMutexClassクラスは、システムレベルのミューテックス関数とミューテックス同期オブジェクトをカプセル化するクラスです。ミューテックスの作成は、オブジェクトをインスタンス化するときに行い、非ブロック状態のミューテックスを作成します。
このクラスには、LockとUnlockという2つのメンバ関数があります。Lockは、ミューテックスをロックして呼び出し元のスレッドに割り当てるメンバ関数です。ミューテックスは、呼び出し元のスレッドがUnlockメンバ関数で解放するまでは、そのスレッドにロックされたままとなります。ロック状態のミューテックスのLockメンバ関数を呼び出して取得しようとしたスレッドはブロックされ、CPU使用率が低い待ち状態に置かれます。ブロックしているスレッドがミューテックスを解放するまではその状態が続きます。
CMutexClass::CMutexClass(void) :m_bCreated(TRUE) { #ifdef WINDOWS m_mutex = CreateMutex(NULL,FALSE,NULL); if( !m_mutex ) m_bCreated = FALSE; #else pthread_mutexattr_t mattr; pthread_mutexattr_init( &mattr ); pthread_mutex_init(&m_mutex,&mattr); #endif memset(&m_owner,0,sizeof(ThreadId_t)); } CMutexClass::~CMutexClass(void) { #ifdef WINDOWS WaitForSingleObject(m_mutex,INFINITE); CloseHandle(m_mutex); #else pthread_mutex_lock(&m_mutex); pthread_mutex_unlock(&m_mutex); pthread_mutex_destroy(&m_mutex); #endif } /** * * Lock * the same thread cannot lock the same mutex * more than once * **/ void CMutexClass::Lock() { ThreadId_t id = CThread::ThreadId(); try { if(CThread::ThreadIdsEqual(&m_owner,&id) ) // the mutex is already locked by this thread throw "\n\tthe same thread can not acquire a mutex twice!\n"; #ifdef WINDOWS WaitForSingleObject(m_mutex,INFINITE); #else pthread_mutex_lock(&m_mutex); #endif m_owner = CThread::ThreadId(); } catch( char *psz ) { #ifdef WINDOWS MessageBoxA(NULL,&psz[2],"Fatal exception CMutexClass::Lock", MB_ICONHAND); exit(-1); #else cerr << "Fatal exception CMutexClass::Lock : " << psz; #endif } } /** * * Unlock * releases a mutex. Only the thread that acquires * the mutex can release it. * **/ void CMutexClass::Unlock() { ThreadId_t id = CThread::ThreadId(); try { if( ! CThread::ThreadIdsEqual(&id,&m_owner) ) throw "\n\tonly the thread that acquires a mutex can release it!"; memset(&m_owner,0,sizeof(ThreadId_t)); #ifdef WINDOWS ReleaseMutex(m_mutex); #else pthread_mutex_unlock(&m_mutex); #endif } catch ( char *psz) { #ifdef WINDOWS MessageBoxA(NULL,&psz[2],"Fatal exception CMutexClass::Unlock", MB_ICONHAND); exit(-1); #else cerr << "Fatal exception CMutexClass::Unlock : " << psz; #endif } }
| 関数 | 説明 |
| void CMutexClass() | コンストラクタ |
| void Lock() | ミューテックスオブジェクトをロックする(ブロック状態の場合は待機する) |
| void Unlock() | ブロック状態だったミューテックスをロック解除/ブロック解除する |
int g_iStorage = 0; CMutexClass MyMutex; void StoreValue( int *pInt ) { MyMutex.Lock(); //the gate keeper. only one thread //allowed in at a time g_iStorage = *pInt; //protected data, critical code section MyMutex.Unlock(); //unblocks, allowing another thread to //access g_iStorage }
