临界区和互斥量相似,但是临界区被限制在单个进程内,而互斥量可以在进程间共享。所有临界区在进程内实现速速比互斥量快很多,如果不需要在进程间共享资源应优先选择临界区而不是互斥量。
void InitializeCriticalSection (LPCRITICAL_SECTION lpCriticalSection):
创建临界区
void EnterCriticalSection (LPCRITICAL_SECTION lpCriticalSection):
当线程需要加入被临界区保护的代码段时,需调用该函数。如果该临界区已近被其它线程占用则该线程将阻塞,直到其它线程释放临界区
BOOL TryEnterCriticalSection (LPCRITICAL_SECTION lpCriticalSection):
当线程需要加入被临界区保护的代码段时,调用该函数时不会引起阻塞,如果该临界区已经被其他线程占用则直接返回FALSE,否则返回TRUE
void LeaveCriticalSection (LPCRITICAL_SECTION lpCriticalSection):
线程离开临界区时应调用该函数
void DeleteCriticalSection (LPCRITICAL_SECTION lpCriticalSection):
当不使用临界区时,使用该函数删除临界区
// MyThread.cpp : Defines the entry point for the console application. //
#include "stdafx.h" #include <windows.h> #include <commctrl.h>
CRITICAL_SECTION MyCS;
void CRITICAL_SECTION_TEST(INT32 nThread) { EnterCriticalSection(&MyCS); printf("Thread %d is running/n",nThread); LeaveCriticalSection(&MyCS); }
DWORD MyThread1(VOID) { while(1) { CRITICAL_SECTION_TEST(1); Sleep(1000); }
return 0; }
DWORD MyThread2(VOID) { while(1) { CRITICAL_SECTION_TEST(2); Sleep(1000); }
return 0; }
int _tmain(int argc, _TCHAR* argv[]) { HANDLE hThread1; HANDLE hThread2;
InitializeCriticalSection(&MyCS);
hThread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread1, NULL, 0, NULL); if(hThread1) { printf("CreateThread MyThread1 success/r/n"); } else { printf("CreateThread MyThread1 error/r/n"); return -1; }
hThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread2, NULL, 0, NULL); if(hThread2) { printf("CreateThread MyThread2 success/r/n"); } else { printf("CreateThread MyThread2 error/r/n"); return -1; }
while(1) { Sleep(1000); }
CloseHandle(hThread1); CloseHandle(hThread2);
return 0; }
|