dispatch_get_specific 与 dispatch_get_current_queue 一样,无法解决队列死锁的问题。难道是我写法有误?

以下代码是dispatch_get_current_queue 无法避免死锁的代码

- (void)test{
    dispatch_queue_t queueA = dispatch_queue_create("queueA", NULL);
    dispatch_queue_t queueB = dispatch_queue_create("queueB", NULL);
    NSLog(@"A======%@, B=====%@",queueA, queueB);
    dispatch_sync(queueA, ^{
        NSLog(@"A-------%@", dispatch_get_current_queue());
        dispatch_sync(queueB, ^{
            NSLog(@"B-------%@", dispatch_get_current_queue());
            if(queueA != dispatch_get_current_queue()){
                dispatch_sync(queueA, ^{ // queueA同步死锁

                 });
            }
        });
    });
}

以下代码是dispatch_get_specific无法避免死锁的代码,与dispatch_get_current_queue是一模一样的,根本不像满世界的博客说的那样,用dispatch_queue_set_specific 和 dispatch_get_specific 来避免死锁。

    const void * const dispatchSerialQueueSpecificKey = &dispatchSerialQueueSpecificKey;
    dispatch_queue_t queue = dispatch_queue_create("hahahahahahah", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_set_specific(queue,dispatchSerialQueueSpecificKey, (__bridge void *)self, NULL);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_sync(queue, ^{
            id hh = (__bridge id)dispatch_get_specific(dispatchSerialQueueSpecificKey);
            const char * ha = dispatch_queue_get_label(dispatch_get_current_queue());
            NSLog(@">>>>>>%p == %p , %s , %@ ",self,hh,ha, [NSThread currentThread]);
            dispatch_sync(dispatch_queue_create("ieueiwue", DISPATCH_QUEUE_SERIAL), ^{
                id hh1 = (__bridge id)dispatch_get_specific(dispatchSerialQueueSpecificKey);
                const char * ha1 = dispatch_queue_get_label(dispatch_get_current_queue());
                NSLog(@">>>>>>2 %p == %p , %s , %@ ",self,hh1,ha1,[NSThread currentThread]);
                if (hh1 != self) {
                    dispatch_sync(queue, ^{ // queue同步死锁
                        NSLog(@">>>>>>>66666");
                    });
                }
            });
        });
    });

打印结果是

>>>>>>0x2832f1ac0 == 0x2832f1ac0 , hahahahahahah , <NSThread: 0x2832e9580>{number = 3, name = (null)}

>>>>>>2 0x2832f1ac0 == 0x0 , ieueiwue , <NSThread: 0x2832e9580>{number = 3, name = (null)}

从打印结果来看,hh1 用 dispatch_get_specific 取出来的是0x0,并没有取到 dispatch_queue_set_specific 塞进去的self。

造成了与dispatch_get_current_queue一样的后果,队列死锁。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值