加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

线程依赖

发布时间:2020-12-14 05:07:15 所属栏目:百科 来源:网络整理
导读:/* * 假设有A、B、C三个操作,要求: 1. 3个操作都异步执行 2. 操作C依赖于操作B 3. 操作B依赖于操作A */ - ( void )dependency{ // 创建一个队列 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; queue.maxConcurrentOperationCount = 3 ; //
/**
 假设有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{
    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,^{
        //wait信号量-1(少一个可用资源)
        dispatch_wait(semaphore0,DISPATCH_TIME_FOREVER);
        NSLog(@"依赖别人的资源");
        dispatch_semaphore_signal(semaphore1);
    });
    
    //thread1
    //这里有arr的赋值操作,需要最先执行,否则其他地方打印都为空
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,^{
        for(int i = 0; i < 3; i ++)
        {
            [arr addObject:[NSNumber numberWithInt:i]];
        }
        NSLog(@"被依赖的资源 ---> %@",arr);
        //signal相当于信号量+1(多一个可用资源)
        dispatch_semaphore_signal(semaphore0);
    });
    
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读