std::atomic原子变量实现DoubleBuffer。
class DoubleBuffer
{
private:
std::atomic<uint32_t> _used_index; //原子变量
std::string _records[2];
public:
DoubleBuffer();
~DoubleBuffer();
};
DoubleBuffer::DoubleBuffer()
{
}
DoubleBuffer::~DoubleBuffer()
{
}
DoubleBuffer::update() {
uint32_t unused_index = 1 - _used_index;
_records[unused_index] = "new data";
_used_index = unused_index;
}
std::string DoubleBuffer::get_record() {
return _records[_used_index];
}