Linux中的异步Swift处理无法正常工作 [英] Asynchronous Swift processing in Linux not working

查看:66
本文介绍了Linux中的异步Swift处理无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Swift 4.0异步处理在Linux中如何工作。

I'm trying to understand how Swift 4.0 asynchronous processing works in Linux.

查看文档和一些答案我想到了一个简单的例子:

After looking at the documentation and some answers on SO I came up with this simple example:

import Dispatch
import Glibc

DispatchQueue.main.asyncAfter(deadline: .now()) {
    print("Done!")
}

print("Sleeping for 2 seconds...")
usleep(2 * 1_000_000)

print("Exiting...")

但是,仅打印:

Sleeping for 2 seconds...
Exiting...

为什么它不打印完成!吗?我想念什么?我该如何写一个简单的并行处理示例?

Why does it not print Done!? What am I missing? How do I write a simple parallel processing example?

推荐答案

我认为问题出在使用 main 队列。

I think the problem was using the main queue. If I instead create a new queue, it works as expected.

import Dispatch
import Glibc

DispatchQueue(label: "worker").asyncAfter(deadline: .now()) {
    print("Doing work...")
    usleep(1 * 1_000_000)
    print("Work done")
}

print("Sleeping for 2 seconds...")
usleep(2 * 1_000_000)

print("Exiting...")

打印出预期结果:

Sleeping for 2 seconds...
Doing work...
Work done!
Exiting...

这篇关于Linux中的异步Swift处理无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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