1

I'm working as a support engineer, and in the dump of a failing process, I see that there are some locks.

Using Windbg (Visual Studio is not able to handle the call stacks correctly) I've found that one function (ClassName::F()) is coming back. That function uses a critical section and calls for a subfunction (ClassName::f_sub()), who's calling the same critical section, in a nutshell:

int ClassName::f_sub(){
  EnterCriticalSection(&m_cs);
  ...
  LeaveCriticalSection(&m_cs);
  return ...;
}

int ClassName::F() {
  EnterCriticalSection(&m_cs);
  ...
  int temp = f_sub();
  ...
  LeaveCriticalSection(&m_cs);
  return ...;
}

Every time it's the same critical section m_cs (a property of ClassName) being used.

In my opinion, this makes following sequence possible:

Thread 1 : F()     : Enter the critical section. (Thread 1 is in)
Thread 1 : f_sub() : Enter the critical section. (Thread 1 is in)
Thread 1 : f_sub() : Leave the critical section. (Thread 1 is out)
Thread 2 : F()     : Enter the critical section. (Thread 2 is in) 

=> WRONG! Thread 2 should be forced to wait for Thread 1 leaving the critical section via F().

Is my analysis correct and does this mean that it's advised to have different critical sections for main and sub functions?

Dominique
  • 16,450
  • 15
  • 56
  • 112

1 Answers1

1

Is my analysis correct and does this mean that it's advised to have different critical sections for main and sub functions?

From Microsoft Docs (emphasis mine):

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.

So no, what you described should not happen. It is perfectly fine to enter the critical section multiple times and it is required to leave it exactly as many times.

tkausl
  • 13,686
  • 2
  • 33
  • 50
  • Re, "...[the same thread] can make additional calls to EnterCriticalSection..." There's a name for that. It's commonly known as a _[reentrant lock](https://en.wikipedia.org/wiki/Reentrant_mutex)_ – Solomon Slow Apr 19 '19 at 13:13