Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active May 28, 2021 14:40
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save kristopherjohnson/0677fac83e9aaf9f266d to your computer and use it in GitHub Desktop.
Save kristopherjohnson/0677fac83e9aaf9f266d to your computer and use it in GitHub Desktop.
Simple demo of dispatch_group_async/dispatch_group_notify/dispatch_group_wait in Swift
import Foundation
let notified = dispatch_semaphore_create(0)
let group = dispatch_group_create()
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
for n in 0..<20 {
dispatch_group_async(group, queue) {
let timeInterval = Double(arc4random_uniform(1000)) * 0.01
NSThread.sleepForTimeInterval(timeInterval)
println("Finish task \(n)")
}
}
dispatch_group_notify(group, queue) {
// This block will be executed when all tasks are complete
println("All tasks complete")
dispatch_semaphore_signal(notified)
}
// Block this thread until all tasks are complete
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
// Wait until the notify block signals our semaphore
dispatch_semaphore_wait(notified, DISPATCH_TIME_FOREVER)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment