gpt4 book ai didi

ios - 为什么 Dispatch_group_notify 在不同的环境下工作不同?

转载 作者:行者123 更新时间:2023-11-29 11:37:42 25 4
gpt4 key购买 nike

第一种情况是我创建了一个命令行工具应用程序,然后运行这段代码。

    NSLog(@"Main:%@", [NSThread currentThread]);

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, queue, ^{
NSLog(@"Task1:%@", [NSThread currentThread]);
});

dispatch_group_async(group, queue, ^{
NSLog(@"Task2:%@", [NSThread currentThread]);
});

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"Finish:%@", [NSThread currentThread]);
});

登录终端是

    Main:<NSThread: 0x1028033b0>{number = 1, name = main}
Task2:<NSThread: 0x10040f0f0>{number = 2, name = (null)}
Task1:<NSThread: 0x1006008d0>{number = 3, name = (null)}

如果我想在 queue 中显示上次登录并替换 main queue

     dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"Finish:%@", [NSThread currentThread]);
});

使用队列

     dispatch_group_notify(group, queue, ^{
NSLog(@"Finish:%@", [NSThread currentThread]);
});

终端打印了最后一条日志,但为什么不能在Main队列中撤销呢?

当我将此代码复制到简单的 iOS 应用程序时。一切正常:

Main:<NSThread: 0x600000070ac0>{number = 1, name = main}
Task2:<NSThread: 0x6000002633c0>{number = 3, name = (null)}
Task1:<NSThread: 0x600000263480>{number = 4, name = (null)}
MainFinish:<NSThread: 0x600000070ac0>{number = 1, name = main}

我尝试在“命令工具行”中的 Task1 上添加 sleep(1),但它似乎阻塞了队列并且只打印 log:Task2.... 但这一切都在简单的 iOS 应用程序。

为什么会导致这些不同?

最佳答案

image here

与其他在创建时激活的队列不同,您应该调用 dispatch_main() 方法来执行提交给主线程的 block

image here

同样的代码在iOS Application中运行良好的原因是应用程序启动了一个默认的runloop,它按照一定的规则执行提交到主队列的任务,比如UI更新通知。

引用如下:

swift-corelibs-libdispatch

Concurrency Programming Guide

关于ios - 为什么 Dispatch_group_notify 在不同的环境下工作不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48202082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com