从互斥对象返回值

Return value from Mutex

本文关键字:返回值 对象      更新时间:2023-10-16

我有一个互斥的例子。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和函数返回之间的另一个线程更改。但是你真正需要的是互斥锁的作用域保护。

c++ 11:

int Class::NextValue()
{
   std::lock_guard<std::mutex> lock(mutex);
   ++CurrentValue;
   ++CurrentValue;
   return CurrentValue;
} // mutex unlocked on exiting this scope.