//生产者消费者
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
NSMutableArray *array = [[NSMutableArray alloc] init];
dispatch_queue_t queue = dispatch_queue_create("cn.chutong.www", DISPATCH_QUEUE_CONCURRENT);
int max_count = 10000;
//生产
dispatch_async(queue, ^{
while (YES) {
if (array.count >= max_count) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
int count = random()%10;
sleep(0.05f);
[array addObject:[NSString stringWithFormat:@"%d",count]];
// dispatch_semaphore_signal(semaphore);
NSLog(@"生产了%d",count);
}
});
//消费
dispatch_async(queue, ^{
while (YES) {
if (array.count>=max_count) {
NSLog(@"消费了%ld", array.count);
// dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// [array removeLastObject];
[array removeAllObjects];
dispatch_semaphore_signal(semaphore);
}
}
});
iOS生产者消费者问题
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 1.当代种种事件不同于历史之处,在于我们不知道它们会产生什么后果。 2.经验和利益的偶然结合,往往会向人们揭示...