Skip to content

Instantly share code, notes, and snippets.

@vukcevich
Forked from kristopherjohnson/DispatchGroupDemo.swift
Last active August 29, 2015 14:25
Show Gist options
  • Save vukcevich/c09fe1c31e00fb56d24d to your computer and use it in GitHub Desktop.
Save vukcevich/c09fe1c31e00fb56d24d 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