Skip to content

Instantly share code, notes, and snippets.

@weihanglo
Last active December 26, 2017 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save weihanglo/b017d3b138d1cd6612b517deff68ba1e to your computer and use it in GitHub Desktop.
Save weihanglo/b017d3b138d1cd6612b517deff68ba1e to your computer and use it in GitHub Desktop.
Grand Central Dispatch (GCD, Dispatch in Swift 3) DispatchGroup and DispatchSemaphore Demo
// 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