Last active
November 28, 2024 00:14
-
-
Save brennanMKE/cbf987e45e1ccbe0fe18acb613a4b227 to your computer and use it in GitHub Desktop.
Sync
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
private let lock = NSRecursiveLock() // Lock for thread-safe access | |
func sync<T>(@_implicitSelfCapture operation: @escaping @Sendable () throws -> T) rethrows -> T { | |
lock.lock() | |
defer { lock.unlock() } | |
return try operation() | |
} | |
func doWork() { | |
sync { | |
// do work safely | |
print("I'm working here!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment