在这种特定情况下,避免数据竞争的更好方法是什么?

我正在编写一个程序,其中一个类具有一些变量,并创建一个分离的(异步/并行)线程以在无限的while循环中更新其私有(private)变量。此外,此类还具有在主线程中不时访问其私有(private)变量的函数:

#include "UART.h"
class Example
{
private:
  double x;
  double y;
  UART &uart;
public:
  Example::Example(UART u) : uart(u), x(0), y(0) {};

  void Example::run()
  {
     while(1)
     {
         x = uart.read() // Here x is being filled with some other values
     }
  }

  void Example::getX()
  {
     // Data race
      y = this->x*2;
   }
};

int main(int argc, char** argv)
{
  Example example(u);
  std::thread t1(&Example::run, example);
  t1.detach();

  example.getX();
}

因此,使用上面的代码,更好的解决方案是避免数据竞争和x的未定义行为?

它在函数mutex中是否具有getx():
// mtx will be created in Example private member sector
void Example::getX()
{
   mtx.lock();
   y = this->x*2;
   mtx.unlock();
}

还是将x设为原子更好?
std::atomic<double> x;

最佳答案

在这里,不仅atomic足够了,而且memory_order_relaxed(而不是简单的赋值)就足够了,因为没有其他内存写需要供其他线程使用。

09-30 15:45
查看更多