Skip to content

Instantly share code, notes, and snippets.

@junebash
Last active February 6, 2023 18:42
Show Gist options
  • Save junebash/87114073983b55352ef49aefa6c23442 to your computer and use it in GitHub Desktop.
Save junebash/87114073983b55352ef49aefa6c23442 to your computer and use it in GitHub Desktop.
A basic task queue
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