1.Critical Sections(臨界區)
from http://www.4ucode.com/Study/Topic/1012632
代碼中如果有不能由兩個或兩個以上線程同時執行的部分,可以用臨界區來使這部分的代碼執行串列化。它只能在一個獨立的進程或一個獨立的應用程式中使用。使用方法如下:
//申明
var
oCSect: TCriticalSection; // 臨界區物件,保證多線程時存取資料模組的安全
//創建
oCSect := TCriticalSection.Create;
//進入臨界區
oCSect.Enter;
try
dosomething...//保護的代碼
finally
//離開臨界區
oCSect.Leave;
end;
//釋放臨界區
oCSect.Free;
2.Mutex(互斥對象)
var
oCSect: TCriticalSection; // 臨界區物件,保證多線程時存取資料模組的安全
//創建
oCSect := TCriticalSection.Create;
//進入臨界區
oCSect.Enter;
try
dosomething...//保護的代碼
finally
//離開臨界區
oCSect.Leave;
end;
//釋放臨界區
oCSect.Free;
是用於串列化訪問資源的全局物件。我們首先設置互斥物件,然後訪問資源,最後釋放互斥物件。在設置互斥物件時,如果另一個線程(或進程)試圖設置相同的互斥物件,該線程將會停下來,直到前一個線程(或進程)釋放該互斥物件為止。注意它可以由不同應用程式共用。使用方法如下:
//申明
hMutex: HWND;
//創建
hMutex:=CreateMutex(nil,false,nil);
try
WaitForSingleObject(hMutex,INFINITE);
dosomething...//保護的代碼
finally
ReleaseMutex(hMutex);
end;
//銷毀
CloseHandle(hMutex)
3.Semaphore(信號量)
hMutex: HWND;
//創建
hMutex:=CreateMutex(nil,false,nil);
try
WaitForSingleObject(hMutex,INFINITE);
dosomething...//保護的代碼
finally
ReleaseMutex(hMutex);
end;
//銷毀
CloseHandle(hMutex)
它與互斥物件相似,但它可以計數。例如可以允許一個給定資源同時同時被三個線程訪問。其實Mutex就是最大計數為一的 Semaphore。使用方法如下:
//申明
hSemaphore: THandle; // 併發許可數控制碼
//建立信號燈 創建物件時指定最大可同時訪問的線程數
//CreateSemaphore(lpSemaphoreAttributes As SECURITY_ATTRIBUTES, ByVal lInitialCount As Long, ByVal lMaximumCount As Long, ByVal lpName As String);
hSemaphore:= CreateSemaphore(nil,lInitialCount,lMaximumCount,lpName)
try
WaitForSingleObject(hSemaphore,INFINITE);
dosomething...//保護的代碼
finally
ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount)
end;
//銷毀
CloseHandle(hSemaphore)
hSemaphore: THandle; // 併發許可數控制碼
//建立信號燈 創建物件時指定最大可同時訪問的線程數
//CreateSemaphore(lpSemaphoreAttributes As SECURITY_ATTRIBUTES, ByVal lInitialCount As Long, ByVal lMaximumCount As Long, ByVal lpName As String);
hSemaphore:= CreateSemaphore(nil,lInitialCount,lMaximumCount,lpName)
try
WaitForSingleObject(hSemaphore,INFINITE);
dosomething...//保護的代碼
finally
ReleaseSemaphore(hSemaphore, lReleaseCount, lpPreviousCount)
end;
//銷毀
CloseHandle(hSemaphore)
from http://www.4ucode.com/Study/Topic/1012632