单个生产者和单个消费者模型(spsc)

本文通过一个C++示例介绍了如何使用Boost库中的无锁单生产者单消费者队列(SPSC)。该示例展示了多线程环境下生产者与消费者的交互过程,并验证了无锁队列的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// LockFree.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <boost/thread/thread.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <iostream>

#include <boost/atomic.hpp>

	int producer_count = 0;
boost::atomic_int consumer_count (0);

boost::lockfree::spsc_queue<int, boost::lockfree::capacity<1024> > spsc_queue;

const int iterations = 10000000;

void producer(void)
{
	int count = 0;
	for (int i = 0; i != iterations; ++i) {
		int value = ++producer_count;
		while (!spsc_queue.push(value)) //队列满则等待。
			++count;
	}
	std::cout << "full " << count << " times\n";
}

boost::atomic<bool> done (false);

void consumer(void)
{
	int value;
	while (!done) { //生产者还在生产
		while (spsc_queue.pop(value)) //如果有产品就消费
			++consumer_count;
	}

	while (spsc_queue.pop(value)) //生产者停工
		++consumer_count;
}

int main(int argc, char* argv[])
{
	using namespace std;
	cout << "boost::lockfree::queue is ";
	if (!spsc_queue.is_lock_free())
		cout << "not ";
	cout << "lockfree" << endl;

	boost::thread producer_thread(producer);
	boost::thread consumer_thread(consumer);

	producer_thread.join();
	done = true;
	consumer_thread.join();

	cout << "produced " << producer_count << " objects." << endl;
	cout << "consumed " << consumer_count << " objects." << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值