gpt4 book ai didi

c++ - C++ 11中与std::atomic的同步

转载 作者:行者123 更新时间:2023-12-03 13:16:32 40 4
gpt4 key购买 nike

我有以下代码可以在Intel处理器上很好地运行,但是在ARM处理器上却产生怪异的数据。
我怀疑这是一个同步问题。
基本上,我有一个生产者线程定期调用setLiveData(...)和一个消费者线程也定期调用getLiveData(...)
.h文件

class DataHandler{
public:
...
private:

LiveDataValue lastValues_;
bool lastValuesValid;
};
.cpp文件
bool DataHandler::getLiveData(LiveDataValue *val)
{
if(this->lastValuesValid){
*val = this->lastValues_;
return true;
}else
return false;
}

void DataHandler::setLiveData(LiveDataValue val)
{
this->lastValuesValid = false;
this->lastValues = val;
this->lastValuesValid = true;
}
仅通过阅读代码,我认为我需要确保 setLiveData是原子的,即在生产者线程位于 getLiveData(...)中间的情况下,消费者线程无法调用 setLiveData(...)
我找到了 this answer并尝试使用它来修复代码:
.h文件
class DataHandler{
public:
...
private:

LiveDataValue lastValues_;
std::atomic<bool> lastValuesValid;
};
.cpp文件
bool DataHandler::getLiveData(LiveDataValue *val)
{
while (!this->lastValuesValid.load(std::memory_order_acquire))
{
std::this_thread::yield();
}

if(this->lastValuesValid){
*val = this->lastValues_;
return true;
}else
return false;
}

void DataHandler::setLiveData(LiveDataValue val)
{
this->lastValuesValid_.store(false, std::memory_order_release);
this->lastValues = val;
this->lastValuesValid_.store(true, std::memory_order_release);
}
我的问题是,我永远不会退出阅读器线程调用的getLiveData中的while循环。这是为什么?
编辑:LiveDataValue是一个复杂的 union typedef,此处未详细介绍。

最佳答案

您的问题是您的代码不同步,而不是循环没有结束。

if(this->lastValuesValid){
*val = this->lastValues_;
return true;
}else
return false;
您可以检查最后一个值是否有效,为真,以及在分配它们时这些值无效。此后不会立即进行任何有效性检查,它只是告诉您在过去的某个时刻它们在哪里有效。
template<class T>
struct mutex_guarded {
template<class F>
void read( F&& f ) const {
auto l = std::unique_lock<std::mutex>(m);
f(t);
}
template<class F>
void write( F&& f ) {
auto l = std::unique_lock<std::mutex>(m);
f(t);
}
private:
mutable std::mutex m;
T t;
};
这是一个简单的包装程序,用于序列化对任意类型的某些数据的访问。
class DataHandler{
public:
...
private:

struct Data {
LiveDataHolder lastValues_;
bool lastValuesValid_ = false;
};
mutex_guarded<Data> data_;
};
然后
bool DataHandler::getLiveData(LiveDataValue *val) const
{
bool bRet = false;
data_.read([&](Data const& data_){
bRet = data_.lastValuesValid_;
if (!bRet) return;
*val = data_.lastValues;
});
return bRet;
}

void DataHandler::setLiveData(LiveDataValue val)
{
data_.write([&](Data & data_){
data_.lastValues = std::move(val);
data_.lastValuesValid = true;
});
}
将自动修改有效字段和值字段。
.read(lambda).write(lambda)中完成的所有操作都是在锁定互斥锁的情况下完成的。 lambda可以通过 T const&T&传递,具体取决于它是读操作还是写操作,并且没有其他方法可以访问 protected 数据。
(将其扩展为支持读取器/写入器锁相对容易,但是保持简单是一个很好的经验法则,因此我只是使用互斥锁来编写它)

关于c++ - C++ 11中与std::atomic的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66423561/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com