|
1 | | -# dispatch-async |
| 1 | +# dispatch-async |
| 2 | + |
| 3 | +## ⚠️ WARNING - This is an 🧪experimental🧪 repository and should not be adopted at large. |
| 4 | + |
| 5 | +DispatchAsync is a temporary experimental repository aimed at implementing missing Dispatch support in the SwiftWasm toolchain. |
| 6 | +Currently, [SwiftWasm doesn't include Dispatch](https://book.swiftwasm.org/getting-started/porting.html#swift-foundation-and-dispatch). |
| 7 | +But, SwiftWasm does support Swift Concurrency. DispatchAsync implements a number of common Dispatch API's using Swift Concurrency |
| 8 | +under the hood. |
| 9 | + |
| 10 | +Dispatch Async does not provide blocking API's such as `DispatchQueue.sync`, primarily due to the intentional lack of blocking |
| 11 | +API's in Swift Concurrency. |
| 12 | + |
| 13 | +# Toolchain Adoption Plans |
| 14 | + |
| 15 | +DispatchAsync is not meant for consumption abroad directly as a new Swift Module. Rather, the intention is to provide eventual integration |
| 16 | +as a drop-in replacement for Dispatch when compiling to Wasm. |
| 17 | + |
| 18 | +There are a few paths to adoption into the Swift toolchain |
| 19 | + |
| 20 | +- DispatchAsync can be emplaced inside the [libDispatch repository](https://github.com/swiftlang/swift-corelibs-libdispatch), and compiled |
| 21 | +into the toolchain only for wasm targets. |
| 22 | +- DispatchAsync can be consumed in place of libDispatch when building the Swift toolchain. |
| 23 | + |
| 24 | +Ideally, with either approach, this repository would transfer ownership to the swiftlang organization. |
| 25 | + |
| 26 | +# DispatchSemaphore Limitations |
| 27 | + |
| 28 | +The current implementation of `DispatchSemaphore` has some limitations. Blocking threads goes against the design goals of Swift Concurrency. |
| 29 | +The `wait` function on `DispatchSemaphore` goes against this goal. Furthermore, most wasm targets run on a single thread from the web |
| 30 | +browser, so any time the `wait` function ends up blocking the calling thread, it would almost certainly hang a single-threaded wasm |
| 31 | +executable. |
| 32 | + |
| 33 | +To navigate these issues, there are some limitations: |
| 34 | + |
| 35 | +- For wasm compilation targets, `DispatchSemaphore` assumes single-threaded execution, and lacks various safeguards that would otherwise |
| 36 | +be needed for multi-threaded execution. This makes the implementation much easier. |
| 37 | +- For wasm targets, calls to `signal` and `wait` must be balanced. An assertion triggers if `wait` is called more times than `signal`. |
| 38 | +- DispatchSemaphore is deprecated for wasm targets, and AsyncSemaphore is encouraged as the replacement. |
| 39 | +- For non-wasm targets, DispatchSemaphore is simply a typealias for `AsyncSemaphore`, and provides only a non-blocking async `wait` |
| 40 | +function. This reduces potential issues that can arise from wait being a thread-blocking function. |
0 commit comments