发现
dispatch_queue_get_label()
最近在看SDWebimage代码,发现之前对线程和队列的认识不够清晰。在源码中看到这个方法。
if (dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) == dispatch_queue_get_label(queue)) {
block();
} else {
dispatch_async(queue, block);
}
- dispatch_queue_get_label(dispatch_queue_t queue)
/** Explain: Returns the label specified for the queue when the queue was created. The label of the queue, or NULL if the queue was not provided a label during initialization. */
- DISPATCH_CURRENT_QUEUE_LABEL
/** Explain: Pass this constant to the [dispatch_queue_get_label] function to retrieve the label of the current queue. */
传这个常量到 dispatch_queue_get_label 函数,去检索到当前队列的标签
以前的做法
+ (void)runInMainThreadBlock:(void (^)(void))block {
if ([NSThread isMainThread]) {
block();
block = nil;
} else {
dispatch_async(dispatch_get_main_queue(), ^{
block();
});
block = nil;
}
}
这种写法只判断了当前是否在主线程运行,而对于特定的框架(如:MapKit / VektorKit),某些API不仅依赖于主线程,而且依赖于主队列,因此检查当前队列比检查当前线程更安全。
参考:http://blog.benjamin-encz.de/post/main-queue-vs-main-thread/