Skip to content

Instantly share code, notes, and snippets.

@maxcampolo
Created April 19, 2016 19:07
Show Gist options
  • Save maxcampolo/76c91ddd9e983a5d661462cbc358fa83 to your computer and use it in GitHub Desktop.
Save maxcampolo/76c91ddd9e983a5d661462cbc358fa83 to your computer and use it in GitHub Desktop.
Mutual exclusion in Swift (equivalent to @synchronized in obj-c)
/**
Function that locks an object while it is being acted upon in the closure parameter.
Rethrows allows the function to throw an error for throwing closures or not for non-throwing closures (do not need `try` for non-throwing closures).
parameter lock: Object to be sync'd
parameter closure: Code of critical section
*/
public func synchronized<T>(lock: AnyObject, @noescape closure: () throws -> T) rethrows -> T {
objc_sync_enter(lock)
defer {
objc_sync_exit(lock)
}
return try closure()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment