Skip to content

Instantly share code, notes, and snippets.

@soxjke
Created March 20, 2020 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soxjke/728a1367162036da3c52aa36ef709e5c to your computer and use it in GitHub Desktop.
Save soxjke/728a1367162036da3c52aa36ef709e5c to your computer and use it in GitHub Desktop.
DispatchQueue.recursiveSync
extension DispatchQueue {
private struct Const {
static let rSyncKey = DispatchSpecificKey<NSString>()
}
var recursiveSyncEnabled: Bool {
set { self.setSpecific(key: Const.rSyncKey, value: newValue ? (label as NSString) : nil)}
get { self.getSpecific(key: Const.rSyncKey) != nil }
}
func recursiveSync(_ closure: @escaping () -> ()) {
let specific = DispatchQueue.getSpecific(key: Const.rSyncKey)
return (specific != nil && specific == self.getSpecific(key: Const.rSyncKey)) ?
closure() :
sync(execute: closure)
}
}
DispatchQueue.main.recursiveSyncEnabled = true
for _ in 1...1000 {
DispatchQueue.main.recursiveSync {
print("a")
}
}
DispatchQueue.global().async {
for _ in 1...1000 {
DispatchQueue.main.recursiveSync {
print("b")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment