Windows提供的临界区对是CRITICAL_SECTION,使用步骤如下:
(1)创建临界区对象 CRITICAL_SECTION Section;
查阅代码可知,CRITICAL_SECTION是一个结构体,声明如下
typedef RTL_CRITICAL_SECTION CRITICAL_SECTION;
typedef struct _RTL_CRITICAL_SECTION {
PRTL_CRITICAL_SECTION_DEBUG DebugInfo;
//
// The following three fields control entering and exiting the critical
// section for the resource
//
LONG LockCount;
LONG RecursionCount;
HANDLE OwningThread; // from the thread's ClientId->UniqueThread
HANDLE LockSemaphore;
ULONG_PTR SpinCount; // force size on 64-bit systems when packed
} RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION;
(2)初始化临界区 InitializeCriticalSection(&Section);
(3)进入临界区,禁止其他线程访问 EnterCriticalSection(&Section);或者使用TryEnterCriticalSection
声明如下: