在 Swift CLI 中使用 GCD [英] Using GCD in Swift CLI

查看:45
本文介绍了在 Swift CLI 中使用 GCD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我尝试在 CLI 中使用 GCD.为了测试它,我写了一些这样的代码:

So I'm trying to use GCD in the CLI. To test it out i wrote some code like this:

import Foundation

var i = 0

print("a: ",i)

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {

    for n in 1..<10{
        i++
    }

    print("c: ",i)

    dispatch_async(dispatch_get_main_queue()){
        print("d: ",i)
    }
}

print("b: ",i)

sleep(5)
print("e: ",i)

这个输出是:一:0乙:0时间:9电子:9

the output of this is: a: 0 b: 0 c: 9 e: 9

几秒钟后打印最后一行.我想知道的是在 d 发生了什么?我放在那个块中的任何东西似乎都没有执行.当我在 iOS 中使用它时,这工作正常,只是在 CLI 中无效.

with the last line printing a few seconds later. What I'm trying to find out is what happened at d? Nothing I put in that block seems to execute. This works fine when I use it in iOS, just not in the CLI.

推荐答案

CLI 缺乏应用程序的持久性.它在 d 有机会被打印之前就结束了(终止).

The CLI lacks the persistence of an app. It came to an end (terminated) before d had a chance to be printed.

正如@user3441734 正确指出的那样,您可以在 CLI 中通过调用 dispatch_main() 作为退出前的最后一件事来解决此问题.这个调用有效地迫使我们立即进入主队列并在退出之前拉出主队列块并执行它.

As @user3441734 rightly points out, you can work around this in the CLI by calling dispatch_main() as the last thing before exit. This call effectively forces us to dip into the main queue right now and pull out the main-queued block and execute it, before exiting.

这篇关于在 Swift CLI 中使用 GCD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆