源码如下:
#pragma once
#include
template
class DoubleBuffer {
public:
DoubleBuffer() : cur_index(0) {}
T& getWorkingBuffer(std::memory_order order = std::memory_order_seq_cst) {
return buffers[cur_index.load(order)];
}
T& getBackupBuffer(std::memory_order order = std::memory_order_seq_cst) {
return buffers[1 ^ cur_index.load(order)];
}
void switchBuffer(std::memory_order order = std::memory_order_seq_cst) {
cur_index.fetch_xor(1, order);
}
private:
T buffers[2];
std::atomic cur_index;
};