//生产者消费者
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);
}
}
});
网友评论