Is it valid to nest a critical section?

前端 未结 3 1306
时光取名叫无心
时光取名叫无心 2020-12-16 13:19

For example, would this be valid?

CRITICAL_SECTION cs;

::InitializeCriticalSection( &cs );

::EnterCriticalSection( &cs );      // First level
::Ent         


        
相关标签:
3条回答
  • 2020-12-16 13:34

    To validate the other two posts. Quick look at Critical section in WinDbg shows that cricital section maintains an integer variable to hold Recursion counts.

    0:001> dt RTL_CRITICAL_SECTION
    +0x000 DebugInfo : Ptr32 _RTL_CRITICAL_SECTION_DEBUG
    +0x004 LockCount : Int4B
    +0x008 RecursionCount : Int4B
    +0x00c OwningThread : Ptr32 Void
    +0x010 LockSemaphore : Ptr32 Void
    +0x014 SpinCount : Uint4B 
    

    RecursionCount - It is possible for a thread to acquire a critical section more than once. This field indicates how many times the same thread has acquired the critical section. By default, the value of this field is 0, indicating that there is no thread owning the critical section.

    0 讨论(0)
  • 2020-12-16 13:36

    From the documentation:

    After a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. The thread enters the critical section each time EnterCriticalSection and TryEnterCriticalSection succeed. A thread must call LeaveCriticalSection once for each time that it entered the critical section.

    0 讨论(0)
  • 2020-12-16 13:42

    Yes it is valid to enter the same critical section while already inside it. From the docs:

    After a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. The thread enters the critical section each time EnterCriticalSection and TryEnterCriticalSection succeed. A thread must call LeaveCriticalSection once for each time that it entered the critical section.

    0 讨论(0)
提交回复
热议问题