Last active
December 26, 2017 04:24
-
-
Save weihanglo/b017d3b138d1cd6612b517deff68ba1e to your computer and use it in GitHub Desktop.
Grand Central Dispatch (GCD, Dispatch in Swift 3) DispatchGroup and DispatchSemaphore Demo
This file contains hidden or 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 Dispatch | |
import Foundation | |
let semaphore = DispatchSemaphore(value: 0) | |
let group = DispatchGroup() | |
let globalQueue = DispatchQueue.global(qos: .default) | |
print("Tasks started!!!") | |
print() | |
// Run asynchronous closures | |
for i in 0..<10 { | |
globalQueue.async(group: group) { | |
let timeInterval = Double(arc4random_uniform(300)) / 100 | |
Thread.sleep(forTimeInterval: timeInterval) | |
print("Task #\(i) finished!!") | |
// signal and increase the semaphore | |
if i == 5 { | |
semaphore.signal() | |
} | |
} | |
} | |
// DispatchGroup.notify is an asynchoruous method that return immediately. | |
group.notify(queue: globalQueue) { | |
// This closure will be executed after all tasks done. | |
print() | |
print("All tasks done!!!") | |
} | |
// Wait until the someone signals the semaphore | |
semaphore.wait() // wait forever, block this thread | |
print("semaphore count decreased to zero") | |
// Block this thread until all tasks in the group are complete | |
// The enum `.distantFuture` is equal to `DISPATCH_TIME_FOREVER` in Objc and Swift 2.3 | |
group.wait(timeout: .distantFuture) | |
print("group complete!!!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment