简体   繁体   English

为什么Boost scoped_lock无法解锁互斥锁?

[英]Why is Boost scoped_lock not unlocking the mutex?

I've been using boost::mutex::scoped_lock in this manner: 我一直以这种方式使用boost::mutex::scoped_lock

void ClassName::FunctionName()
{
    {  
     boost::mutex::scoped_lock scopedLock(mutex_);
     //do stuff
      waitBoolean=true;
    }
    while(waitBoolean == true ){
        sleep(1);
    }
    //get on with the thread's activities
}

Basically it sets waitBoolean, and the other thread signals that it is done by setting waitBoolean to false; 基本上,它设置了waitBoolean,其他线程则通过将waitBoolean设置为false来表明已完成。

This doesn't seem to work, however, because the other thread can't get a lock on mutex_ !! 但是,这似乎不起作用,因为另一个线程无法锁定互斥锁!

I was assuming that by wrapping the scoped_lock in brackets I would be terminating its lock. 我假设通过将scoped_lock括在方括号中来终止其锁定。 This isn't the case? 不是这样吗 Reading online says that it only gives up the mutex when the destructor is called. 在线阅读说,只有在调用析构函数时,它才会放弃互斥量。 Won't it be destroyed when it goes out of that local scope? 它超出当地范围时是否会被销毁?

Signaling part of code: 信号部分代码:

while(running_){
   boost::mutex::scoped_lock scopedLock(mutex_);
   //Run some function that need to be done...
   if(waitBoolean){
      waitBoolean=false;
   }
}

Thanks! 谢谢!

To synchronize two threads use a condition variable. 要同步两个线程,请使用条件变量。 That is the state of the art way to synchronize two threads the way you want : 这是按照您想要的方式同步两个线程的最新方法:

Using boost, the waiting part is something like : 使用boost,等待的部分是这样的:

void BoostSynchronisationPoint::waitSynchronisation()
{
    boost::unique_lock<boost::mutex> lock(_mutex);

    _synchronisationSent = false;
    while(!_synchronisationSent)
    {
        _condition.wait(lock); // unlock and wait
    }
}

The notify part is something like : 通知部分类似于:

void BoostSynchronisationPoint::sendSynchronisation()
{
    {
        boost::lock_guard<boost::mutex> lock(_mutex);
        _synchronisationSent = true;
    }

    _condition.notify_all();
}

The business with _synchronisationSent is to avoid spurrious wakeups : see wikipedia 使用_synchronisationSent进行业务是避免突然唤醒:请参阅Wikipedia

The scoped_lock should indeed be released at the end of the scope. 实际上,scoped_lock应该在作用域的末尾释放。 However you don't lock the waitBoolean when you're looping on it, suggesting you don't protect it properly other places as well - eg where it's set to false, and you'll end up with nasty race conditions. 但是,当您在其上循环时,请不要锁定waitBoolean,这表明您在其他地方也没有适当地保护它-例如,在将其设置为false的地方,最终会遇到讨厌的竞争条件。

I'd say you should use a boost::condition_variable to do this sort of things, instead of sleep + thread-unsafe checking. 我想说你应该使用boost :: condition_variable来做这种事情,而不是睡眠+线程不安全的检查。

我也建议将waitBoolean标记为volatile,但是您必须使用条件甚至更好的障碍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM