Created
September 29, 2022 07:02
-
-
Save drewmccormack/b2178fec0313fe714a6ddd6ae309fe1a to your computer and use it in GitHub Desktop.
A Queue (FIFO) built from an actor.
This file contains 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
actor Queue { | |
private var tasks: [() async -> Void] = [] | |
func enqueue(_ task: @escaping () async -> Void) { | |
tasks.append(task) | |
Task { await runNext() } | |
} | |
private func runNext() async { | |
guard !tasks.isEmpty else { return } | |
let task = tasks.removeFirst() | |
await task() | |
if !tasks.isEmpty { | |
Task { await runNext() } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment