临界区负锁计数 [英] Critical section negative lock count

查看:133
本文介绍了临界区负锁计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调试一个死锁问题,调用堆栈显示线程正在等待某些事件。

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

代码使用关键部分作为同步原语,我认为这存在一些问题这里。
调试器还指向其他线程拥有的关键部分,但锁计数为-2。
根据我的理解,锁计数> 0表示关键部分被一个或多个线程锁定。

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?

推荐答案

我假设您正在谈论MFC中的CCriticalSection类。我认为您正在寻找正确的关键部分。我发现,如果对Lock()函数的调用次数少于Unlock()调用的次数,则关键部分的锁定计数可能为负。我发现这通常发生在以下类型的代码中:

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();
}

乍一看,这段代码看起来非常安全。但是请注意,我直接使用的是CCriticalSection的Unlock()方法,而不是CSingleLock的Unlock()方法。现在发生的是,当函数退出时,其析构函数中的CSingleLock再次调用关键部分的Unlock(),并且其锁定计数变为负数。此后,应用程序将处于不良状态,奇怪的事情开始发生。如果您使用的是MFC关键部分,请检查是否存在此类问题。

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.

这篇关于临界区负锁计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆