//生产者消费者
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
self.array = [[NSMutableArray alloc] init];
dispatch_queue_t queue = dispatch_queue_create("cn.chutong.www", DISPATCH_QUEUE_CONCURRENT);
//生产
dispatch_async(queue, ^{
while (YES) {
int count = random()%10;
sleep(1);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[self.array addObject:[NSString stringWithFormat:@"%d",count]];
dispatch_semaphore_signal(semaphore);
NSLog(@"生产了%d",count);
}
});
//消费
dispatch_async(queue, ^{
while (YES) {
if (self.array.count>0) {
NSLog(@"消费了%@",self.array.lastObject);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[self.array removeLastObject];
dispatch_semaphore_signal(semaphore);
}
}
});
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交