美文网首页
GCD's Main Queue vs. Main Th

GCD's Main Queue vs. Main Th

作者: 大风天上来 | 来源:发表于2019-02-15 11:40 被阅读0次

发现

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. */

以前的做法

+ (void)runInMainThreadBlock:(void (^)(void))block {
    if ([NSThread isMainThread]) {
        block();
        block = nil;
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            block();
        });
        block = nil;
    }
}
这种写法只判断了当前是否在主线程运行,而对于特定的框架(如:MapKit / VektorKit),某些API不仅依赖于主线程,而且依赖于主队列,因此检查当前队列比检查当前线程更安全。

相关文章

网友评论

      本文标题:GCD's Main Queue vs. Main Th

      本文链接:https://www.haomeiwen.com/subject/harpeqtx.html