同步生产者,使用者和生产者队列

编程入门 行业动态 更新时间:2024-10-23 09:25:34
本文介绍了同步生产者,使用者和生产者队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个生产者和一个消费者。生产者用对象填充其内部队列,消费者逐一地取得这些对象。我想要使​​cosumer与生产者同步,这样当没有对象准备就绪时,消费者阻塞,并且我想使生产者与自身同步,以便在队列满时停止产生(并且当有空间时再次启动) 。我怎么做?我可以使用 NSConditionalLock 解决一个更简单的情况,但是队列中的问题看起来更复杂。

objectsReady 和 bufferFreeSlots : / p>

@implementation生产者 - (id)getNextObject { [objectsReady wait]; id anObject = [[buffer objectAtIndex:0] retain]; [buffer removeObjectAtIndex:0]; [bufferFreeSlots signal]; return [anObject autorelease]; } - (void)decodeLoop { while(1){ [bufferFreeSlots wait]; [buffer push:[self produceAnObject]]; [objectsReady signal]; } } @end

bufferFreeSlots 初始化为最大队列大小。到目前为止,它似乎工作,但上帝知道这是一种信仰的行为,而不是一个坚定的信心。

I have a producer and a consumer. Producer fills its internal queue with objects, consumer takes these objects one by one. I want to synchronize the cosumer with the producer, so that the consumer blocks when there are no objects ready, and I want to synchronize the producer with itself, so that it stops producing when the queue is full (and starts again when there’s space). How do I do that? I was able to solve a simpler case without the queue using NSConditionalLock, but with the queue the problem looks more complex.

解决方案

I ended up using two semaphores, objectsReady and bufferFreeSlots:

@implementation Producer - (id) getNextObject { [objectsReady wait]; id anObject = [[buffer objectAtIndex:0] retain]; [buffer removeObjectAtIndex:0]; [bufferFreeSlots signal]; return [anObject autorelease]; } - (void) decodeLoop { while (1) { [bufferFreeSlots wait]; [buffer push:[self produceAnObject]]; [objectsReady signal]; } } @end

The bufferFreeSlots is initialized to the maximum queue size. So far it seems to work, but God knows this is an act of faith, not a solid confidence.

更多推荐

同步生产者,使用者和生产者队列

本文发布于:2023-10-15 01:01:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492778.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:生产者   队列   使用者

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!