Asynchronous Swift processing in Linux not working

大憨熊 提交于 2020-01-15 05:24:09

问题


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...")

However, this only prints:

Sleeping for 2 seconds...
Exiting...

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


回答1:


You have to call dispatchMain() to start the GCD event loop:

Executes blocks submitted to the main queue

Example:

DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
    print("Done!")
    exit(0)
}

print("Starting main event loop...")
dispatchMain()



回答2:


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...")

Prints out the expected result:

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



回答3:


Dispatch is not preemptive. Blocks that are submitted to a non-concurrent queue will be processed in order, and no block will be processed until the block before them finishes. You put your block on the main queue, which corresponds to the main thread, however, the main thread is busy sleeping until it exits, and never has a chance to do dispatch queue work.

Martin R mentioned dispatchMain, though another option would be RunLoop.main.run(mode: .defaultRunLoopMode, before: .distantFuture), which would only run the runloop once, allowing the program to exit afterwards.



来源:https://stackoverflow.com/questions/48597036/asynchronous-swift-processing-in-linux-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!