[英]Should I use std::atomic or std::mutex to avoid the thread race?
What is the better way to avoid the data race in this specific scenario?在这种特定情况下避免数据竞争的更好方法是什么?
I am writing a program where a class has some variable and creates a detached (async/parallel) thread to update its private variable in an infinite while loop.我正在编写一个程序,其中一个类有一些变量并创建一个分离的(异步/并行)线程以在无限 while 循环中更新其私有变量。 Also, this class has a function that accesses its private variable time to time in the main thread:
此外,这个类有一个函数,可以在主线程中不时访问其私有变量:
#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();
}
So with the code above, what is the better solution to avoid a data race and undefined behavior of x
?那么对于上面的代码,避免
x
的数据竞争和未定义行为的更好解决方案是什么?
Is it having mutex
in function getx()
:在函数
getx()
是否有mutex
:
// mtx will be created in Example private member sector
void Example::getX()
{
mtx.lock();
y = this->x*2;
mtx.unlock();
}
Or is it better to make x
as atomic?还是将
x
设为原子更好?
std::atomic<double> x;
这里不仅atomic
足够,而且memory_order_relaxed
(而不是简单的赋值)就足够了,因为没有其他内存写入需要提供给另一个线程使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.