Created
June 19, 2024 19:18
-
-
Save rnapier/553329510858f13d932b69a10981359d to your computer and use it in GitHub Desktop.
Ordering async tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Built with Swift 6 (Xcode 16b1) | |
actor Accumulator { | |
static let shared = Accumulator() | |
var values: [String] = [] | |
// A couple of approaches, neither of which works. | |
func add(value: String) { values.append(value) } | |
nonisolated func addSync(value: String) { Task { await add(value: value) } } | |
} | |
final class C: Sendable { | |
func run() { | |
// Neither of these approaches seem to work, though both together do, so it's a race condition. | |
Accumulator.shared.addSync(value: "sync") | |
// Task { await Accumulator.shared.add(value: "async") } | |
} | |
} | |
C().run() | |
// How can I ensure that `values` is updated before `values` returns without making `run` async? | |
// I'm not asking for `run` to block until it's done. I'm asking for this `await` to block until | |
// the previous operation completes. | |
print(await Accumulator.shared.values) // This return [] | |
print(await Accumulator.shared.values) // This returns ["sync"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment