Created
October 4, 2016 18:24
-
-
Save misbell/c2f5aea998ba64174a23e538172243f1 to your computer and use it in GitHub Desktop.
DispatchQueue and DispatchGroup in Swift 3.0 as of Oct 4 2016
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
let dispatchGroup = DispatchGroup() | |
let dq = DispatchQueue.global(qos: .utility) | |
dq.async { | |
for i in 0...3{ | |
dq.async { | |
print("\n i - \(i)") | |
dispatchGroup.enter() | |
(DispatchQueue.global(qos: .userInitiated)).async(group: dispatchGroup, qos: .userInitiated, flags: .assignCurrentContext) { | |
() -> Void | |
in | |
Thread.sleep(forTimeInterval: 2.0) | |
print("\nBlock 1\n") | |
dispatchGroup.leave() | |
} | |
(DispatchQueue.global(qos: .userInitiated)).async(group: dispatchGroup, qos: .userInitiated, flags: .assignCurrentContext) { | |
() -> Void | |
in | |
Thread.sleep(forTimeInterval: 5.0) | |
print("\nBlock 2\n") | |
dispatchGroup.leave() | |
} | |
(DispatchQueue.global(qos: .userInitiated)).async(group: dispatchGroup, qos: .userInitiated, flags: .assignCurrentContext) { | |
() -> Void | |
in | |
Thread.sleep(forTimeInterval: 1.0) | |
print("\nBlock 3\n") | |
dispatchGroup.leave() | |
} | |
dispatchGroup.notify(queue: DispatchQueue.global(qos: .userInitiated)) { | |
() -> Void | |
in | |
print("\nBlock 4\n") | |
} | |
} | |
} | |
} |
here, I get rid of the variable:
let dispatchGroup = DispatchGroup()
(DispatchQueue.global(qos: .userInitiated)).async {
for i in 0...3{
(DispatchQueue.global(qos: .userInitiated)).async {
print("\n i - \(i)")
dispatchGroup.enter()
(DispatchQueue.global(qos: .userInitiated)).async(group: dispatchGroup, qos: .userInitiated, flags: .assignCurrentContext) {
() -> Void
in
Thread.sleep(forTimeInterval: 2.0)
print("\nBlock 1\n")
dispatchGroup.leave()
}
(DispatchQueue.global(qos: .userInitiated)).async(group: dispatchGroup, qos: .userInitiated, flags: .assignCurrentContext) {
() -> Void
in
Thread.sleep(forTimeInterval: 5.0)
print("\nBlock 2\n")
dispatchGroup.leave()
}
(DispatchQueue.global(qos: .userInitiated)).async(group: dispatchGroup, qos: .userInitiated, flags: .assignCurrentContext) {
() -> Void
in
Thread.sleep(forTimeInterval: 1.0)
print("\nBlock 3\n")
dispatchGroup.leave()
}
dispatchGroup.notify(queue: DispatchQueue.global(qos: .userInitiated)) {
() -> Void
in
print("\nBlock 4\n")
}
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
also shows a neat way to call .async on the main queue without assigning it to a var: (DispatchQueue.global(qos: .userInitiated)).async
this is a translation of earlier code from Nishant Basin:
https://gist.github.com/nbhasin2/735cd80298b5d47852f2/