Swift 是否有任何本机并发和多线程支持?

Does Swift have any native concurrency and multi-threading support?

我正在编写一个 Swift 客户端与嵌入式系统上的服务器(用 C 语言编写)进行通信。它与 iOS/OSX 无关,因为我使用的是最近发布的 Ubuntu 版本。

Swift是否有对并发的原生支持?我知道 Apple 不鼓励开发人员使用线程并鼓励通过 GCD 将任务移交给调度队列。问题是 GCD 似乎只适用于 Darwin(而 NSThread 是 Cocoa 的一部分)。

例如,C++11 和 Java 将线程和并发作为其标准库的一部分。我知道像 unix 上的 posix 这样的平台特定的东西可以在某种 C 包装器下使用,但对我来说,这真的破坏了首先使用 Swift 的意义(干净,易于理解的代码等)。

2021 年来了...

从 Swift 5.5 开始,more options are available 喜欢 async/await 编程模型和参与者。

仍然没有直接操作线程,这是(截至目前)设计选择。

If you’ve written concurrent code before, you might be used to working with threads. The concurrency model in Swift is built on top of threads, but you don’t interact with them directly. An asynchronous function in Swift can give up the thread that it’s running on, which lets another asynchronous function run on that thread while the first function is blocked.

2015 年原始答案

引用自Swift's GitHub,有一个关于“进化”的自述文件:

Concurrency: Swift 3.0 relies entirely on platform concurrency primitives (libdispatch, Foundation, pthreads, etc.) for concurrency. Language support for concurrency is an often-requested and potentially high-value feature, but is too large to be in scope for Swift 3.0.

我想这意味着在可预见的未来管道中不会有线程的语言级“原语”。