Skip to content

Instantly share code, notes, and snippets.

@kk-vv
Created February 6, 2024 03:45
Show Gist options
  • Save kk-vv/199bdf9205e47587ced5cc586810386b to your computer and use it in GitHub Desktop.
Save kk-vv/199bdf9205e47587ced5cc586810386b to your computer and use it in GitHub Desktop.
Convert multi async Tasks to sync queue
func fetchFromRemote(by ids: [MKAssetId]) {
let group = DispatchGroup()
let queue = DispatchQueue(label: "felix.hu.remote.assets")
let semaphore = DispatchSemaphore(value: 1)
for id in ids {
queue.async { // queue.async still sync but new thread, if queue.sync is main thread will cause dead lock
group.enter()
semaphore.wait()
Task {
do {
// await action
let result = try await fetch(by: id)
group.leave()
semaphore.signal()
} catch {
group.leave()
semaphore.signal()
}
}
}
}
group.notify(queue: .main) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment