Skip to content

Instantly share code, notes, and snippets.

@cntrump
Created November 20, 2023 09:22
Show Gist options
  • Save cntrump/f04714f64e56d7100d52ed20ab8cd4bd to your computer and use it in GitHub Desktop.
Save cntrump/f04714f64e56d7100d52ed20ab8cd4bd to your computer and use it in GitHub Desktop.
@synchronized in Swift
import ObjectiveC
@discardableResult
public func synchronized<T>(_ lock: AnyObject, closure: () -> T) -> T {
let lock_ = lock
objc_sync_enter(lock_)
defer { objc_sync_exit(lock_) }
return closure()
}
@cntrump
Copy link
Author

cntrump commented Nov 20, 2023

Example code:

func foo() {
    synchronized(self) {
        // do something
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment