Created
October 15, 2020 17:18
-
-
Save Galeas/eae03cf2590ee0e662643096c6ef5dc8 to your computer and use it in GitHub Desktop.
Swift 3+ GCD's dispatch_once
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 static var _onceTracker = [String]() | |
func once(file: String = #file, function: String = #function, line: Int = #line, _ block:() -> Void) { | |
let token = file + ":" + function + ":" + String(line) | |
once(token: token, block) | |
} | |
/// Executes a block of code, associated with a unique token, only once. The code is thread safe and will | |
/// only execute the code once even in the presence of multithreaded calls. | |
/// | |
/// - Parameters: | |
/// - token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID | |
/// - block: Block to execute once | |
func once(token: String, _ block:() -> Void) { | |
objc_sync_enter(self) | |
defer { objc_sync_exit(self) } | |
if DispatchQueue._onceTracker.contains(token) { | |
return | |
} | |
DispatchQueue._onceTracker.append(token) | |
block() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment