循环队列 - 生产者与消费者模型

该博客通过实例展示了如何使用循环队列无锁地实现一个生产者与消费者模型。队列容量为10,生产者每秒将递增整数推入队列,而消费者每3秒从队列中弹出一个元素。当队列满时,生产者会等待,同样,队列空时消费者也会等待。

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

循环队列可以实现一个生产者与一个消费者模型, 不使用锁。

 

循环队列:容量大小为10

生产者线程:把从0递增的整数依次push到队列,队列满了就等1s(尾部不存储,也就是最大存9个数)。

消费者线程:每3s从队列pop一个元素。

[xiongli@localhost data_struct]$ ./a.out            
push 0 at data[0]
push 1 at data[1]
push 2 at data[2]
push 3 at data[3]
push 4 at data[4]
push 5 at data[5]
push 6 at data[6]
push 7 at data[7]
push 8 at data[8]
the queue is full!
the queue is full!
the queue is full!
                pop 0 at data[0]
push 9 at data[9]
the queue is full!
the queue is full!
the queue is full!
                pop 1 at data[1]
push 10 at data[0]
the queue is full!
the queue is full!
the queue is full!
                pull 2 at data[2]
push 11 at data[1]
the queue is full!
the queue is full!
the queue is full!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值