Created
March 20, 2020 10:39
-
-
Save soxjke/728a1367162036da3c52aa36ef709e5c to your computer and use it in GitHub Desktop.
DispatchQueue.recursiveSync
This file contains 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
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