线程依赖

/**
 假设有A、B、C三个操作,要求:
 1. 3个操作都异步执行
 2. 操作C依赖于操作B
 3. 操作B依赖于操作A
 */
- (void)dependency{
    //创建一个队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    queue.maxConcurrentOperationCount = 3; //可开辟线程的最大数量
    
    //创建三个任务
    NSBlockOperation *operationA = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"A任务当前线程为:%@", [NSThread currentThread]);
    }];
    NSBlockOperation *operationB = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"B任务当前线程为:%@", [NSThread currentThread]);
    }];
    NSBlockOperation *operationC = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"C任务当前线程为:%@", [NSThread currentThread]);
    }];
    
    //设置任务相互依赖
    [operationB addDependency:operationA];
    [operationC addDependency:operationB];
    
    //添加到操作队列中(自动异步执行任务,并发)
    [queue addOperation:operationA];
    [queue addOperation:operationB];
    [queue addOperation:operationC];
    
}

- (void)GCDSemaphore{
    /*
     dispatch_semaphore_signal  这个函数会使传入的信号量的值加1
     dispatch_semaphore_wait  这个函数会使传入的信号量的值减1
     */
    NSMutableArray *arr = [NSMutableArray array];
    //创建信号量,值为0
    dispatch_semaphore_t semaphore0 = dispatch_semaphore_create(0);
    dispatch_semaphore_t semaphore1 = dispatch_semaphore_create(0);
    
    //thread3
    //希望它是最后执行的,让它依赖thread2
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        //DISPATCH_TIME_FOREVER表示一直等着,直到semaphore为0执行.
        //如果写15的话,就代表我只等15纳秒,15纳秒后,不管信号量是否为0,都执行下面的代码.
        //阻塞当前线程一直到semaphore1为0
        dispatch_semaphore_wait(semaphore1, DISPATCH_TIME_FOREVER);
        NSLog(@"最弱的,最后执行");
    });
    
    //thread2
    //等待thread1执行完毕后,执行thread2.(thread2依赖thread1)
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //wait信号量-1(少一个可用资源)
        dispatch_semaphore_wait(semaphore0, DISPATCH_TIME_FOREVER);
        NSLog(@"依赖别人的资源");
        dispatch_semaphore_signal(semaphore1);
    });
    
    //thread1
    //这里有arr的赋值操作,需要最先执行,否则其他地方打印都为空
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        for(int i = 0; i < 3; i ++)
        {
            [arr addObject:[NSNumber numberWithInt:i]];
        }
        NSLog(@"被依赖的资源 ---> %@",arr);
        //signal相当于信号量+1(多一个可用资源)
        dispatch_semaphore_signal(semaphore0);
    });
    
    
}
 

 

posted @ 2018-06-06 23:04  hongsheng  阅读(228)  评论(0编辑  收藏  举报