c++ - 返回是原子的,我应该在 getter 中使用临时的线程安全吗?

标签 c++ multithreading thread-safety atomic getter

是否有必要在这里使用临时线程安全?

 int getVal() {
       this->_mutex.lock();
       int result = this->_val;
       this->_mutex.unlock();
       return result;
 }

我给你拆简单的RAII测试函数

int test()
{
    RAIITest raii; //let's say it's a scoped lock
    return 3;
}


 {
     0x004013ce <_Z4testv>:    push  %ebp
     0x004013cf <_Z4testv+1>:  mov   %esp,%ebp
     0x004013d1 <_Z4testv+3>:  sub   $0x28,%esp
     return 3;
     0x004013d4 <_Z4testv+6>:  lea   -0x18(%ebp),%eax
     0x004013d7 <_Z4testv+9>:  mov   %eax,(%esp)
     0x004013da <_Z4testv+12>: call  0x4167a0 <_ZN8RAIITestD1Ev>  //here destructor is called
     0x004013df <_Z4testv+17>: mov   $0x3,%eax //here result is pushed onto the stack
 }
 0x004013e4 <_Z4testv+22>: leave 
 0x004013e5 <_Z4testv+23>: ret   

编译器是gcc/g++ 3.4.5

最佳答案

如果对 this->_val 的访问是通过 this->_mutex 同步的,那么您无法选择当前代码的编写方式。您需要在解锁互斥量之前阅读 this->_val 并且您必须在返回之前解锁互斥量。 result 变量是获取此操作顺序所必需的。

如果你使用了lock_guard(或者在 Boost 中使用 scoped_lock),那么你不需要使用临时锁,因为当函数返回。例如,使用 C++0x 线程库:

int getVal() {
    std::lock_guard<std::mutex> lock(_mutex);
    return this->_val;
}   // lock is released by lock_guard destructor 

关于c++ - 返回是原子的,我应该在 getter 中使用临时的线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3638895/

相关文章:

java - 如何创建 Cassandra ITrigger 析构函数?

java - Java中PrintStream的线程安全

Python 线程 : locking within while statement

java - 这段代码是否解决了 Java 中的双重检查锁定问题?

c++ - 如何在没有返回它的属性/函数的情况下获取派生接口(interface) (OLE/COM)

c++ - C/C++ : header file not found

c++ - 如何散列 std::regex?

c++ - 如何从 C++ 中的 PWSTR 中提取子字符串

java - 在工作流重新配置时禁止进入工作线程

Python 多线程(while 和 apscheduler)