为了能够判断当前queue是否是之前创建的queue,
我们可以利用dispatch_queue_set_specific和dispatch_get_specific给queue关联一个context data,
后面再利用这个标识获取到context data。
如果可以获取到说明当前上下文是在自己创建的queue中,如果不能获取到context data则表示当前是在其他队列上。
1 NSString *queueKey = @"queueKey1"; 2 dispatch_queue_t queue = dispatch_queue_create("testQueue", DISPATCH_QUEUE_CONCURRENT); 3 dispatch_queue_set_specific(queue, (__bridge const void * _Nonnull)(queueKey) 4 , &queueKey, NULL); 5 6 7 NSLog(@"1.当前线程:%@ 队列:%@", [NSThread currentThread], dispatch_get_current_queue()); 8 9 10 if (dispatch_get_specific((__bridge const void * _Nonnull)(queueKey))) { 11 NSLog(@"2.当前线程:%@ 队列:%@", [NSThread currentThread], dispatch_get_current_queue()); 12 }else{ 13 NSLog(@"3.当前线程:%@ 队列:%@", [NSThread currentThread], dispatch_get_current_queue()); 14 } 15 16 17 dispatch_sync(queue, ^{ 18 19 if (dispatch_get_specific((__bridge const void * _Nonnull)(queueKey))) { 20 NSLog(@"4.当前线程:%@ 队列:%@", [NSThread currentThread], dispatch_get_current_queue()); 21 }else{ 22 NSLog(@"5.当前线程:%@ 队列:%@", [NSThread currentThread], dispatch_get_current_queue()); 23 } 24 });
输出信息
2018-02-13 16:44:13.977719+0800 CGD[14596:276910] 1.当前线程:<NSThread: 0x604000260180>{number = 1, name = main} 队列:<OS_dispatch_queue_main: com.apple.main-thread>
2018-02-13 16:44:13.977900+0800 CGD[14596:276910] 3.当前线程:<NSThread: 0x604000260180>{number = 1, name = main} 队列:<OS_dispatch_queue_main: com.apple.main-thread>
2018-02-13 16:44:13.978047+0800 CGD[14596:276910] 4.当前线程:<NSThread: 0x604000260180>{number = 1, name = main} 队列:<OS_dispatch_queue: testQueue>