#include <iostream>
#include <string>
#include <vector>
#include <atomic>
struct SpinLock {
SpinLock(std::atomic_flag &flag) : flag_(flag) {
while (true == flag_.test_and_set(std::memory_order_acquire)) {
}
}
~SpinLock() {
flag_.clear(std::memory_order_release);
}
private:
std::atomic_flag &flag_;
};
template <class T>
struct BufferBase {
virtual ~BufferBase() = default;
virtual bool try_push(const T &&) = 0;
virtual bool try_pop(T &) = 0;
};
class StringRingBuffer : public BufferBase<std::string> {
public:
struct Item {
Item() : written(false) , flag{ATOMIC_FLAG_INIT} {
}
bool written;
std::string data;
std::atomic_flag flag;
};
public:
StringRingBuffer(size_t size = 1024) : size_(size){
if (0 == size_ || size_ > max_capacity_) {
size_ = max_capacity_;
线程安全ring buffer
最新推荐文章于 2025-11-08 10:01:12 发布
本文介绍了一种使用std::atomic_flag实现的SpinLock机制,并基于此设计了一个StringRingBuffer类,用于线程间字符串数据的高效传递。通过自定义的Item结构,实现了数据的原子写入和读取,确保了线程安全。

最低0.47元/天 解锁文章
2030

被折叠的 条评论
为什么被折叠?



