Objective-C实现生产者消费者问题
生产者-消费者问题是一个经典的多线程问题,它涉及两个或多个线程之间的协作。生产者负责生成数据并将其放入缓冲区,而消费者则从缓冲区中取出数据进行处理。在Objective-C中,我们可以使用NSCondition来实现这一问题。
实现思路
为了确保生产者不会在缓冲区满时继续生产,消费者在缓冲区空时不会继续消费,我们需要使用同步机制。在Objective-C中,NSCondition是一个强大的工具,可以帮助我们实现这一点。
#import <Foundation/Foundation.h>
#define BUFFER_SIZE 5
@interface ProducerConsumerViewController : NSViewController
{NSCondition *condition;NSMutableArray *buffer;NSOperationQueue *queue;}@implementation ProducerConsumerViewController
(void)viewDidLoad)
{[super viewDidLoad];self.buffer = [NSMutableArray new];self.queue = [NSOperationQueue new];self.condition = [NSCondition new];}(void *)producerThread:(NSThread *)thread
{while (true) {[self.condition wait];if ([self.buffer count] < BUFFER_SIZE) {[self.buffer addObject:[NSDate new]];} else {// 缓冲区已满,生产者暂停sleep(1);}}}(void *)consumerThread:(NSThread *)thread
{while (true) {[self.condition wait];if ([self.buffer count] > 0) {[self.buffer removeObjectAtIndex:0];} else {// 缓冲区为空,消费者暂停sleep(1);}}}(void)startThreads
{[self.queue addExecutionThreadWithName:@"生产者" target:self selector:@selector(producerThread:)];[self.queue addExecutionThreadWithName:@"消费者" target:self selector:@selector(consumerThread:)];}(void)stopThreads
{[self.queue cancelAllOperations];}