简体   繁体   English

提升scoped_lock返回行为

[英]boost scoped_lock return behavior

Is the two code segments produce same behavior? 两个代码段是否产生相同的行为? I think it does unless there is something I'm missing. 我认为除非有我缺少的东西,否则它会做到。 Note: I have used this pointer everywhere just to clarify that all variables are member variables of some_class 注意:我在所有地方都使用了此指针,只是为了阐明所有变量都是some_class的成员变量

int some_class::some_func()
{
    boost::scoped_lock lock(this->m_mutex);
    return this->member;
}

int some_class::some_func()
{
    this->m_mutex.lock();
    int a = this->member;
    this->m_mutex.unlock();
    return a;
}

some how these are doing same work but: this is not just about forgetting to call unlock() : an exception may occur while your mutex is locked, and your call to unlock() may never be reached, even though you do not have any return statement between your call to lock() and your call to unlock(); 它们的一些工作方式如何,但是:这不仅是要忘记调用unlock() :互斥体被锁定时可能会发生异常,即使您没有任何调用,也可能永远无法达到对unlock()的调用在对lock()的调用与对unlock()的调用之间返回return语句; like: 喜欢:

m.lock() // m is a mutex
    // do something
    foo(); // If this throws an exception,that your mutex won't get unlocked
    // do something
    m.unlock()

Bur in the case of scoped_lock , the destructor of scoped_lock guard will be invoked during stack unwinding, making sure that associated mutex always gets released. 在使用scoped_lock的情况下,将在堆栈展开期间调用scoped_lock保护的析构函数,以确保始终释放关联的互斥量。

It's the same assuming that int a = this->member; 假设int a = this->member;是相同的int a = this->member; doesn't throw an exception. 不会抛出异常。

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

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