OGeek|极客世界-中国程序员成长平台

标题: ios - 在条件循环中调度队列的问题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:51
标题: ios - 在条件循环中调度队列的问题

-(void) sample
{
    dispatch_queue_t aQueue = dispatch_queue_create("hello-world", NULL);

    __block  int j=0;
    for(int i=0; i<3; ++i){
        dispatch_sync(aQueue, ^{
            j++;
            NSLog(@"I'm in Loop\n");
            if(j==2)
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"I'm in main for the first time\n");
                });
        });
    }
    dispatch_sync(aQueue, ^{
        NSLog(@"I'm in the second task of aQueue\n");
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"I'm just about to exit from the main thread\n");
        });
    });
}

输出:

2016-02-02 17:11:16.226 facebookCustom Post[5078:227956] I'm in Loop
2016-02-02 17:11:16.227 facebookCustom Post[5078:227956] I'm in Loop
2016-02-02 17:11:16.227 facebookCustom Post[5078:227956] I'm in Loop
2016-02-02 17:11:16.227 facebookCustom Post[5078:227840] I'm in the second task of aQueue
2016-02-02 17:11:16.426 facebookCustom Post[5078:227840] I'm in main for the first time
2016-02-02 17:11:16.426 facebookCustom Post[5078:227840] I'm just about to exit from the main thread

代码的输出让我非常惊讶,因为我们第一次同步调度了队列,所以在第一个任务完成之前不应该执行该任务,对吧?那么 I'm in the second task of aQueue 怎么能在 I'm in main first time 之前打印出来呢?



Best Answer-推荐答案


我相信这在 this question 的答案中得到了更完整的回答。并且与 GCD 实现中的优化有关。

这些 block 正在当前(主)线程上执行,而不是在 aQueue 上,作为优化,因此通过 dispatch_get_main_queue() 的任何调用都是“排队”(请原谅双关语)稍后执行,我认为在运行循环的下一次迭代中。

您可以通过使用 NSLog() 而不是 printf() 进行日志记录来获取更多信息,因为这将打印线程 ID。请使用该输出更新您的问题。

这就是我目前所拥有的一切,也许@bbum 会通过并提供更好的答案来澄清。

顺便说一句,这是个好问题。

关于ios - 在条件循环中调度队列的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35150451/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4