Last active
February 6, 2023 18:42
-
-
Save junebash/87114073983b55352ef49aefa6c23442 to your computer and use it in GitHub Desktop.
A basic task queue
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 TaskQueue { | |
private var queuedOperations: [() async -> Void] = [] // should probably be an actual `Queue`/`Deque` type | |
private var currentTask: Task<Void, Never>? | |
private var iterationTask: Task<Void, Never>? | |
init() {} | |
func addOperation(_ operation: @escaping () async -> Void) { | |
if currentTask == nil { | |
currentTask = Task { | |
await operation() | |
self.currentTask = nil | |
} | |
} else { | |
queuedOperations.append(operation) | |
if iterationTask == nil { | |
iterationTask = Task { | |
await self.iterateThroughOperations() | |
self.iterationTask = nil | |
} | |
} | |
} | |
} | |
private func iterateThroughOperations() async { | |
while !queuedOperations.isEmpty { | |
if let currentTask = currentTask { | |
await currentTask.value | |
} | |
let next = queuedOperations.removeFirst() | |
currentTask = Task { | |
await next() | |
self.currentTask = nil | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment