互斥體

互斥體實現了“互相排斥”(mutual exclusion)同步的簡單形式(所以名為互斥體(mutex))。互斥體禁止多個執行緒同時進入受保護的代碼“臨界區”(critical section)。

基本介紹

  • 中文名:互斥體
  • 外文名:mutual exclusion
  • 性質:同步的簡單形式
  • 特點:保護的代碼
簡介,創建,套用,備註信息,

簡介

在任意時刻,只有一個執行緒被允許進入代碼保護區。任何執行緒在進入臨界區之前,必須獲取(acquire)與此區域相關聯的互斥體的所有權。如果已有另一執行緒擁有了臨界區的互斥體,其他執行緒就不能再進入其中。這些執行緒必須等待,直到當前的屬主執行緒釋放(release)該互斥體。什麼時候需要使用互斥體呢?互斥體用於保護共享的易變代碼,也就是,全局或靜態數據。這樣的數據必須通過互斥體進行保護,以防止它們在多個執行緒同時訪問時損壞。

創建

在VC中,我們用CreateMutex函式創建互斥體。
HANDLE WINAPI CreateMutex(
__in_opt LPSECURITY_ATTRIBUTES lpMutexAttributes,
__in BOOL bInitialOwner,
__in_opt LPCTSTR lpName
);

套用

#include <windows.h>
#include <stdio.h>
#define THREADCOUNT 2
HANDLE ghMutex;
DWORD WINAPI WriteToDatabase( LPVOID );
void main()
{
HANDLE aThread[THREADCOUNT];
DWORD ThreadID;
int i;
// Create a mutex with no initial owner
ghMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
if (ghMutex == NULL)
{
printf("CreateMutex error: %d\n", GetLastError());
return;
}
// Create worker threads
for( i=0; i < THREADCOUNT; i++ )
{
aThread[i] = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) WriteToDatabase,
NULL, // no thread function arguments
0, // default creation flags
&ThreadID); // receive thread identifier
if( aThread[i] == NULL )
{
printf("CreateThread error: %d\n", GetLastError());
return;
}
}
// Wait for all threads to terminate
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);
// Close thread and mutex handles
for( i=0; i < THREADCOUNT; i++ )
CloseHandle(aThread[i]);
CloseHandle(ghMutex);
}
DWORD WINAPI WriteToDatabase( LPVOID lpParam )
{
DWORD dwCount=0, dwWaitResult;
// Request ownership of mutex.
while( dwCount < 20 )
{
dwWaitResult = WaitForSingleObject(
ghMutex, // handle to mutex
INFINITE); // no time-out interval
switch (dwWaitResult)
{
// The thread got ownership of the mutex
case WAIT_OBJECT_0:
__try {
// TODO: Write to the database
printf("Thread %d writing to database...\n",
dwCount++;
}
__finally {
// Release ownership of the mutex object
if (! ReleaseMutex(ghMutex))
{
// Handle error.
}
}
break;
// The thread got ownership of an abandoned mutex
// The database is in an indeterminate state
case WAIT_ABANDONED:
return FALSE;
}
}
return TRUE;
}

備註信息

微軟MSDN中關於互斥體的備註
The handle returned byCreateMutexhas MUTEX_ALL_ACCESS access to the new mutex object and can be used in any function that requires a handle to a mutex object.
通過CreateMutex函式返回的句柄擁有MUTEX_ALL_ACCESS 許可權,並且可以在任何函式中請求這個互斥體對象句柄。
Any thread of the calling process can specify the mutex-object handle in a call to one of thewait functions.
任何調用進程的執行緒均可以在WAIT系列的函式中指定這個互斥體對象句柄。
The single-object wait functions return when the state of the specified object is signaled.
單個對象的等待函式(例如:SignalObjectAndWait,WaitForSingleObject, andWaitForSingleObjectEx)會在指定對象的狀態變為受信狀態後返回。
The multiple-object wait functions can be instructed to return either when any one or when all of the specified objects are signaled. When a wait function returns, the waiting thread is released to continue its execution.
多對象的等待函式將等待任意一個或全部對象都變成受信狀態後返回(取決於函式的參數設定)。當等待函式返回,等待執行緒將繼續執行下去。
The state of a mutex object is signaled when it is not owned by any thread.

相關詞條

熱門詞條

聯絡我們