Critical section negative lock count

前端 未结 2 2028
别那么骄傲
别那么骄傲 2020-12-10 04:08

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 th

相关标签:
2条回答
  • 2020-12-10 04:52

    Beware: since Windows Server 2003 (for client OS this is Vista and newer) the meaning of LockCount has changed and -2 is a completely normal value, commonly seen when a thread has entered a critical section without waiting and no other thread is waiting for the CS. See Displaying a Critical Section:

    In Microsoft Windows Server 2003 Service Pack 1 and later versions of Windows, the LockCount field is parsed as follows:

    • The lowest bit shows the lock status. If this bit is 0, the critical section is locked; if it is 1, the critical section is not locked.
    • The next bit shows whether a thread has been woken for this lock. If this bit is 0, then a thread has been woken for this lock; if it is 1, no thread has been woken.
    • The remaining bits are the ones-complement of the number of threads waiting for the lock.
    0 讨论(0)
  • 2020-12-10 05:07

    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 the 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 exits, 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.

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