Last active
August 1, 2017 08:56
-
-
Save yfujiki/77df1725be99a3750634 to your computer and use it in GitHub Desktop.
Simple dispatch_group and dispatch_semaphore sample
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
//: Playground - noun: a place where people can play | |
import Foundation | |
// DispatchGroup sample. | |
// we are waiting for all async blocks to be finished before typing "[Dispatch Group] sample has finished" | |
let group = DispatchGroup() | |
let q1 = DispatchQueue.global(qos: .background) | |
let q2 = DispatchQueue.global(qos: .background) | |
let q3 = DispatchQueue.global(qos: .background) | |
q1.async(group: group) { () -> Void in | |
sleep(1) | |
print("[Dispatch Group] Hello I am here1") | |
} | |
q2.async(group: group) { () -> Void in | |
sleep(2) | |
print("[Dispatch Group] Hello I am here2") | |
} | |
q3.async(group: group) { () -> Void in | |
sleep(3) | |
print("[Dispatch Group] Hello I am here3") | |
} | |
group.wait() | |
print("[Dispatch Group] sample has finished.") | |
// dispatch_semaphore sample. | |
// we are waiting for all async blocks to be finished before typing "[Dispatch Semaphore] sample has finished" | |
// Slightly cumbersome than dispatch_group_async b/c you 'have to' call _wait method for the number of resources. | |
// But it is also beneficial because you can start waiting for number of resources even before async block has started. | |
let semaphore = DispatchSemaphore(value: 0) | |
q1.async { () -> Void in | |
sleep(1) | |
print("[Dispatch Semaphore] Hello I am here1") | |
semaphore.signal() | |
} | |
q2.async { () -> Void in | |
sleep(2) | |
print("[Dispatch Semaphore] Hello I am here2") | |
semaphore.signal() | |
} | |
q3.async { () -> Void in | |
sleep(3) | |
print("[Dispatch Semaphore] Hello I am here3") | |
semaphore.signal() | |
} | |
semaphore.wait() | |
semaphore.wait() | |
semaphore.wait() | |
print("[Dispatch Semaphore] sample has finished.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment