Under what circumstances might a Windows Critical Section have a negative Lock Count?

亡梦爱人 提交于 2019-11-30 19:11:18

Negative lock count is normal behaviour on some Windows versions. Note that the meaning of this field has changed during the lifetime of Windows (see below).

Interpreting these private fields is a tricky business and you may benefit from using dedicated critical section debugging tools.

For example, see this MSDN article gives some details. In particular I think it shows why a value of -6 is perfectly plausible.

Some pertinent excerpts:

Critical sections can be displayed in user mode by a variety of different methods. The exact meaning of each field depends on the version of Microsoft Windows version you are using.

......

In Microsoft Windows 2000, and Windows XP, the LockCount field indicates the number of times that any thread has called the EnterCriticalSection routine for this critical section, minus one. This field starts at -1 for an unlocked critical section. Each call of EnterCriticalSection increments this value; each call of LeaveCriticalSection decrements it. For example, if LockCount is 5, this critical section is locked, one thread has acquired it, and five additional threads are waiting for this lock.

......

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.

It then goes on to explain how to interpret a lock count of -22. So, in summary, it's trickier than you might think!

From here, is a part explanation:

LockCount This is the most important field in a critical section. It is initialized to a value of -1; a value of 0 or greater indicates that the critical section is held or owned. When it's not equal to -1, the OwningThread field (this field is incorrectly defined in WINNT.H—it should be a DWORD instead of a HANDLE) contains the thread ID that owns this critical section. The delta between this field and the value of (RecursionCount -1) indicates how many additional threads are waiting to acquire the critical section.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!