ios - dispatch_sync 总是在主线程上调度一个 block

标签 ios objective-c cocoa-touch cocoa grand-central-dispatch

我正在使用 dispatch_sync 执行一个 block ,并且该 block 已正确执行。但是这个 block 是在主线程上执行的。根据 Apple 文档:

Serial queues (also known as private dispatch queues) execute one task at a time in the order in which they are added to the queue. The currently executing task runs on a distinct thread (which can vary from task to task) that is managed by the dispatch queue.

这意味着(或者我的理解)当前正在执行的进程将在单独的线程上运行。

下面是我用来判断发生了什么的代码。它在 NSURLConnection 的 didReceiveData: 委托(delegate)方法中被调用(我知道我不应该在 didReceiveData: 委托(delegate)方法中这样做——但这只是一个专注于 dispatch_sync 的示例)。以下是我可以采用的不同方式来证明我的结论:

  1. 全局并发队列上使用 dispatch_sync

       dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
            if ([NSThread isMainThread]) {
                NSLog(@"Main Thread");
            }
            else
                NSLog(@"Not on Main Thread");
    
            //Some Process
        });
    

输出-

         Main Thread
         Main Thread 
         Main Thread
         // Main Thread printed till didReceiveData: gets called

  1. 使用 dispatch_queue_create 在自行创建的队列上使用 dispatch_sync

    // Create queue somewhere else like this
    dispatch_queue_t newQueue = dispatch_queue_create("WriteQueue", DISPATCH_QUEUE_SERIAL);
    
    
       dispatch_sync(newQueue, ^{
    
            if ([NSThread isMainThread]) {
                NSLog(@"Main Thread");
            }
            else
                NSLog(@"Not on Main Thread");
    
            //Some Process
        });
    

输出-

         Main Thread
         Main Thread 
         Main Thread
         // Main Thread printed till didReceiveData: gets called

我在这里有点惊讶, block 总是在主线程上执行,或者我错过了什么。因为这似乎与我认为的 Apple Doc 背道而驰。有谁知道这是怎么回事?

更新:根据其他讨论,我了解到 dispatch_sync 在同一线程上执行一个 block (大部分时间),那么为什么 apple docs 的声明与从某种角度。为什么苹果说“当前正在执行的任务运行在一个由调度队列管理的不同线程上(不同任务可能不同)。” 还是我还遗漏了什么?

最佳答案

dispatch_sync() 在同一线程上调度 block ,这是正常的。

编辑

Apple 的文档不仅这样说,还这样说:

As an optimization, this function invokes the block on the current thread when possible.

作为旁注(我知道你在谈论同步版本,但让我们精确一点)我会说 dispatch_async() 也可能导致在同一个线程中执行多个 block 。

关于ios - dispatch_sync 总是在主线程上调度一个 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13972048/

相关文章:

iphone - 将应用程序升级到 iPhone 4 : how to get touches to give low-res screen values

ios - 在Swift或Objective-C中从字符串中删除确切的词组

ios - 使用 FPC 在 iOS 上编程

objective-c - 没有 Core Data 的 NSArrayController 绑定(bind)

iOS URL 请求不工作

iphone - 选择 UITableView 的多行

ios - UIPickerView 没有出现

ios - Air for iOS - 如何处理由于内存有限而导致的崩溃?

ios - ARKIT:使用 PanGesture 移动对象(正确方式)

objective-c - Atom/Electron/Web应用程序和可访问性API(macOS和Windows)