views:

670

answers:

1

I am debugging a deadlock issue and call stack shows that threads are waiting on some events.

Code is using critical section as synchronization primitive I think there is some issue here. Also the debugger is pointing to a critical section that is owned by some other thread,but lock count is -2. As per my understanding lock count>0 means that critical section is locked by one or more threads.

So is there any possibility that I am looking at right critical section which could be the culprit in deadlock.

In what scenarios can a critical section have negative lock count?

+2  A: 

I am assuming that you are talking about CCriticalSection class in MFC. I think you are looking at the right critical section. I have found that the critical section's lock count can go negative if number of calls to Lock() function is less than the number of Unlock() calls. I found that this generally happens in the following type of code:

void f()
{
   CSingleLock lock(&m_synchronizer, TRUE);
   //Some logic here
   m_synchronizer.Unlock();
}

At the first glance this code looks perfectly safe. However, note that I am using CCriticalSection's Unlock() method directly instead of CSingleLock's Unlock() method. Now what happens is that when the function exists CSingleLock in its destructor calls Unlock() of the critical section again and its lock count becomes negative. After this the application will be in a bad shape and strange things start to happen. If you are using MFC critical sections then do check for this type of problems.

Naveen