以下代码是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一样的后果,队列死锁。