从互斥对象返回值
Return value from Mutex
我有一个互斥的例子。CurrentValue
- Class
的成员
int Class::NextValue()
{
mutex.lock();
++CurrentValue;
++CurrentValue;
int localValue = CurrentValue;
mutex.unlock();
return localValue;
}
我不明白为什么用localValue
。下一个代码将不能正常工作?
...
mutex.unlock();
return CurrentValue;
如果return
不是原子CurrentValue
可以在复制构造过程中更改。但在第一个代码示例中可以与localValue
相同?
问题是return CurrentValue;
在互斥锁的保护之外读取CurrentValue
。这意味着另一个线程可能正在"同时"写入它。这是一种数据竞争,因此是未定义的行为。
在任何情况下,代码应该用RAII正确地编写,这个问题甚至不值得考虑。
int Class::NextValue()
{
std::lock_guard<std::mutex> lock(mutex);
++CurrentValue;
++CurrentValue;
return CurrentValue;
}
CurrentValue
可以由调用unlock和函数返回之间的另一个线程更改。但是你真正需要的是互斥锁的作用域保护。
int Class::NextValue()
{
std::lock_guard<std::mutex> lock(mutex);
++CurrentValue;
++CurrentValue;
return CurrentValue;
} // mutex unlocked on exiting this scope.
相关文章:
- 为什么模板类中的对象不能返回值
- 从 lambda 返回的对象将丢失属性值
- 如何通过对象的类属性删除对象,并返回其对象值?
- 为什么按值返回的对象与方法中的对象具有相同的地址?
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- 初始化对象时,可以丢弃新的返回值吗?
- 当设置对象等于另一个函数的返回值时,为什么要调用移动构造函数/分配
- 从右值对象返回成员
- 在没有返回值优化的情况下将两个对象加在一起时,将创建多少个临时对象
- 我应该返回引用堆对象还是返回值
- 转发通用可可对象的返回值
- C++如何在模板中推断可调用对象的类型(参数列表和返回值)
- 在对类对象的赋值进行链接时获取垃圾值,使用按值返回类对象的赋值运算符重载
- 通过值或通过引用返回类对象,这在这里会更快
- 自定义类对象的向量的std::find的返回值
- 为什么getDC返回同一对象的不同值
- 未分配返回未定义对象类型引用的 C++ 函数的返回值时会发生什么情况
- 返回本地对象右值引用,正确或错误
- 从 MapViewOfFile() 的返回值构造自己的对象
- 有没有办法使用 move 而不是复制语义将函数返回值(对象)包装在 Python 中