Skip to content

Instantly share code, notes, and snippets.

@ymyzk
Created August 10, 2015 19:43
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ymyzk/808f72d55bdf0432077b to your computer and use it in GitHub Desktop.
Save ymyzk/808f72d55bdf0432077b to your computer and use it in GitHub Desktop.
Grand Central Dispatch (GCD) dispatch semaphore examples
private func example1() {
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
for i in 0..<10 {
dispatch_async(queue) {
NSLog("Start: \(i)")
sleep(3)
NSLog("End: \(i)")
}
}
}
private func semaphoreExample1() {
let semaphore = dispatch_semaphore_create(2)
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
for i in 0..<10 {
dispatch_async(queue) {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
NSLog("Start: \(i)")
sleep(3)
NSLog("End: \(i)")
dispatch_semaphore_signal(semaphore)
}
}
}
private func semaphoreExample2() {
let semaphore = dispatch_semaphore_create(0)
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
NSLog("Running async task...")
sleep(3)
NSLog("Async task completed")
dispatch_semaphore_signal(semaphore)
}
NSLog("Waiting async task...")
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
NSLog("Continue!")
}
private func semaphoreExample3() {
let semaphore = dispatch_semaphore_create(0)
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let n = 9
for i in 0..<n {
dispatch_async(queue) {
NSLog("\(i): Running async task...")
sleep(3)
NSLog("\(i): Async task completed")
dispatch_semaphore_signal(semaphore)
}
}
NSLog("Waiting async task...")
for i in 0..<n {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
NSLog("\(i + 1)/\(n) completed")
}
NSLog("Continue!")
}
private func semaphoreExample4() {
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let group = dispatch_group_create()
let n = 9
for i in 0..<n {
dispatch_group_async(group, queue) {
NSLog("\(i): Running async task...")
sleep(3)
NSLog("\(i): Async task completed")
}
}
NSLog("Waiting async task...")
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
NSLog("Continue!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment