kakush
kakush

Reputation: 3484

EnterCriticalSection doesn't lock

This is a small part of my code:

CRITICAL_SECTION _cs;
InitializeCriticalSection(&_cs);

 void lock() {
    if (_initizalized){
      EnterCriticalSection(&_cs);
      EnterCriticalSection(&_cs);
      _locked = true;
    }
  }

(I wrote "EnterCriticalSection" twice , because I noticed that this line doesn't work) As I understand, this must cause a deadlock. but it doesn't. why?

Upvotes: 3

Views: 5765

Answers (3)

Roman Ryltsov
Roman Ryltsov

Reputation: 69706

As MSDN says,

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.

Upvotes: 3

Chad
Chad

Reputation: 19042

EnterCriticalSection allows for recursive calls from the same thread. 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.

Upvotes: 7

Wolfgang Ziegler
Wolfgang Ziegler

Reputation: 1685

No the same thread can enter it as often as it wants. CRITICAL_SECTION is used to restrict access between multiple different threads.

Upvotes: 9

Related Questions