gpt4 book ai didi

ios - 了解并发 GCD

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

问题很简单,但我没能找到合理的答案。在这样的代码中

dispatch_queue_t background_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL);

dispatch_async(background_queue, ^{
// do some stuff that takes a long time here...

// follow up with some stuff on the main queue
dispatch_async(dispatch_get_main_queue(), ^{
// Typically updating the UI on the main thread.
});

});

“background_queue”是一个并发队列,因此其中的任务将按顺序开始,但可能不会按相同的顺序完成。所以我们可以在下载图像之前调用更新 UI 的 block 。更多的说明会有所帮助,谢谢。

最佳答案

在这个例子中,两个GCD block 将按顺序完成,因为外部 block 只会在长进程完成后调用内部 block (更正确地说,它可能应该是一个dispatch_sync 在内 block 上)

这将保证顺序,因为后台线程将在主线程即将完成之前以及长任务完成之后调用 gcd block

dispatch_async(background_queue, ^{
// do some stuff that takes a long time here...

// follow up with some stuff on the main queue
dispatch_sync(dispatch_get_main_queue(), ^{ //should be sync not async, but in practice should have little impact if nothing happens after this block
// Typically updating the UI on the main thread.
});
});

这不会,因为两个 gcd block 将同时执行并且不会等待对方完成

dispatch_async(background_queue, ^{
// do some stuff that takes a long time here...
});
// follow up with some stuff on the main queue
dispatch_async(dispatch_get_main_queue(), ^{
// Typically updating the UI on the main thread.
});

关于ios - 了解并发 GCD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42063569/

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