繁体   English   中英

我应该使用 std::atomic 还是 std::mutex 来避免线程竞争?

[英]Should I use std::atomic or std::mutex to avoid the thread race?

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

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

#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的数据竞争和未定义行为的更好解决方案是什么?

在函数getx()是否有mutex

// 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 (而不是简单的赋值)就足够了,因为没有其他内存写入需要提供给另一个线程使用。

暂无
暂无

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

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