同步生产者、消费者和生产者队列

发布于 2024-09-27 09:55:08 字数 184 浏览 5 评论 0原文

我有一个生产者和一个消费者。生产者将对象填充到其内部队列,消费者将这些对象一一取出。我想将消费者与生产者同步,以便消费者在没有准备好对象时阻塞,并且我想将生产者与其自身同步,以便当队列已满时它停止生产(并在有空间时重新开始) 。我该怎么做?我能够使用 NSConditionalLock 在没有队列的情况下解决更简单的情况,但使用队列时问题看起来更复杂。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

昔梦 2024-10-04 09:55:08

您可以考虑使用一对 NSOperationQueues 或调度队列。如果需要,让生产操作(在生产者队列中)在主线程上将消息发送到将消费操作添加到消费者队列的对象。

You might consider using a pair of NSOperationQueues or dispatch queues. Have your production operations (in the producer queue) send messages, on the main thread if necessary, to an object that adds consumption operations to the consumer queue.

心如狂蝶 2024-10-04 09:55:08

我最终使用了两个信号量,objectsReadybufferFreeSlots

@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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文