GCD's Main Queue vs. Main Thread 主队列和主线程

发现

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/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容