想说说被废弃的dispatch_get_current_queue,不得不提一个概念:可重入。
什么是可重入,来自维基百科:若一个程序或子程序可以“安全的被并行执行(Parallel computing)”,则称其为可重入(reentrant或re-entrant)的。
即当该子程序正在运行时,可以再次进入并执行它(并行执行时,个别的执行结果,都符合设计时的预期)。
若一个函数是可重入的,则该函数:
void func(dispatch_queue_t queue, dispatch_block_t block) { if (dispatch_get_current_queue() == queue) { block(); }else{ dispatch_sync(queue, block); } }
然后潜意识里,觉得这个函数是可重入的。
但当target queue恰好是current queue时,同步阻塞会导致死锁。
- (void)deadLockFunc { dispatch_queue_t queueA = dispatch_queue_create("com.yiyaaixuexi.queueA", NULL); dispatch_queue_t queueB = dispatch_queue_create("com.yiyaaixuexi.queueB", NULL); dispatch_sync(queueA, ^{ dispatch_sync(queueB, ^{ dispatch_block_t block = ^{ //do something }; func(queueA, block); }); }); }
1)dispatch_queue_set_specific
dispatch_queue_t queueA = dispatch_queue_create("com.yiyaaixuexi.queueA", NULL); dispatch_queue_t queueB = dispatch_queue_create("com.yiyaaixuexi.queueB", NULL); dispatch_set_target_queue(queueB, queueA); static int specificKey; CFStringRef specificValue = CFSTR("queueA"); dispatch_queue_set_specific(queueA, &specificKey, (void*)specificValue, (dispatch_function_t)CFRelease); dispatch_sync(queueB, ^{ dispatch_block_t block = ^{ //do something }; CFStringRef retrievedValue = dispatch_get_specific(&specificKey); if (retrievedValue) { block(); } else { dispatch_sync(queueA, block); } });
void dispatch_reentrant(void (^block)()) { static NSRecursiveLock *lock = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ lock = [[NSRecursiveLock alloc]init]; }); [lock lock]; block(); [lock unlock]; } dispatch_queue_t queueA = dispatch_queue_create("com.yiyaaixuexi.queueA", NULL); dispatch_block_t block = ^{ //do something }; dispatch_sync(queueA, ^{ dispatch_reentrant(block); });