美文网首页
iOS生产者消费者问题

iOS生产者消费者问题

作者: Adam_潜 | 来源:发表于2018-12-22 12:18 被阅读13次
    
        //生产者消费者
        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生产者消费者问题

          本文链接:https://www.haomeiwen.com/subject/aqjikqtx.html