您好,我已经计划使用boost SPSC队列。我必须有一个侦听器,它总是侦听传入的消息,一旦收到,它会将消息放入队列中,然后返回,再次等待新消息。并且有一个消费者从队列中弹出消息并对其进行处理。
因为我不想让我的侦听器等待锁写入队列,所以我更喜欢boost_lockfree_spsc_queue
。我相信,如果我在初始化队列时设置fixed_sized<false>
,那么队列的大小是不同的。但似乎并非如此。
以下是我的代码:
boost::lockfree::spsc_queue<int, boost::lockfree::fixed_sized<false>> lockFreeQ{10};
void sharedQueue::lockFreeProduce()
{
for(int i = 0; i < 100; i++)
{
lockFreeQ.push(i);
cout<<"--"<<i<<endl;
}
}
void sharedQueue::lockFreeConsume(){
for(int i = 0; i <100; i++){
/* Implement a blocking pop to the queue in order to waste cpu time by busy waiting*/
while(!(lockFreeQ.read_available() > 0))
{
//std::this_thread::yield();
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
}
cout<<" ***"<<lockFreeQ.front()<<endl;
lockFreeQ.pop();
}
}
void sharedQueue:: TestLockFreeQueue()
{
std::thread t1([this]() { this->lockFreeProduce(); });
std::thread t2([this]() { this->lockFreeConsume(); });
t1.join();
t2.join();
}
输出显示了数据的丢失。以下是部分结果。但是它遗漏了87,比如92。
**85
***86
***88
***90
***91
***93
***95
***96
***98
如果它是可变大小的,它应该扩展队列的大小,并且不应该丢失数据。它似乎覆盖了解释过的A consequence of the circular buffer is that when it is full and a subsequent write is performed, then it starts overwriting the oldest data.的数据。在这种情况下,如何在不丢失数据的情况下处理此问题?
谢谢
发布于 2016-12-08 19:16:53
将评论翻译为答案。
该策略对spsc_queue
的作用方式如下:
typedef typename mpl::if_c<runtime_sized,
runtime_sized_ringbuffer<T, allocator>,
compile_time_sized_ringbuffer<T, capacity>
>::type ringbuffer_type;
在您的示例中,它选择runtime_sized_ringbuffer
缓冲区而不是compile_time_sized_ringbuffer
。
两者之间的区别是,在runtime_sized_ringbuffer
的情况下,大小的数组(作为参数传递给构造函数)是使用作为模板参数传递的allocator
分配的,而在compile_time_sized_ringbuffer
的情况下,数组是在堆栈上分配的。
因此,如果您的队列很大,则必须使用runtime_sized_ringbuffer
来代替compile_time_sized_ringbuffer
。
这是唯一的区别,在这两种情况下,底层数据结构都是circular_buffer
。也就是说,即使是在runtime_sized_ringbuffer
的情况下,一旦你完成了对缓冲区中所有位置/索引的写入,最旧的元素也会被覆盖。从下面的代码看,这是非常直接的
static size_t next_index(size_t arg, size_t max_size)
{
size_t ret = arg + 1;
while (unlikely(ret >= max_size))
ret -= max_size;
return ret;
}
如果您确实需要一个无锁列表数据结构,那么您应该看看由Dmitry Vyukov编写的著名的无锁列表数据结构
https://stackoverflow.com/questions/41021283
复制相似问题