Created
April 19, 2016 19:07
-
-
Save maxcampolo/76c91ddd9e983a5d661462cbc358fa83 to your computer and use it in GitHub Desktop.
Mutual exclusion in Swift (equivalent to @synchronized in obj-c)
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
/** | |
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