Skip to content

Instantly share code, notes, and snippets.

@antmd
Forked from ymyzk/semaphore.swift
Created December 5, 2016 15:39
Show Gist options
  • Save antmd/173b5a5337b3cfe8e4ee9f8f31411f06 to your computer and use it in GitHub Desktop.
Save antmd/173b5a5337b3cfe8e4ee9f8f31411f06 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