Forked from kristopherjohnson/DispatchGroupDemo.swift
Last active
August 29, 2015 14:25
-
-
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
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
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