临界区

在编写代码时经常需要使用到多线程,有时多个线程需要执行同一段代码,读写全局变量,此时需要将这段代码保护起来,同一时刻只有一个线程可以执行此代码,这种情况下可以使用临界区。

临界区使用简单,支持线程递归。

CRITICAL_SECTION section = { 0 };

InitializeCriticalSection(&section);

初始化完成后,可以在需要保护的代码前面使用EnterCriticalSection(&section);进入临界区

执行代码结束后,使用LeaveCriticalSection(&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;
RecursionCount为当前线程递归进入临界区的次数,OwningThread为当前占有此临界区的线程ID。
posted @ 2023-02-01 17:44  psj00  阅读(53)  评论(0)    收藏  举报