Last active
October 20, 2021 02:42
-
-
Save orchetect/0ce6c41193297acc67003e9a04659c90 to your computer and use it in GitHub Desktop.
Swift 5 propertyWrapper that wraps a value with a semaphore to prevent overlapping access.
This file contains hidden or 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
/// Wraps a value with a DispatchSemaphore(value: 1) to prevent overlapping access. | |
@propertyWrapper public struct Semaphored<T> { | |
private var value: T | |
private var semaphore = DispatchSemaphore(value: 1) | |
public var wrappedValue: T { | |
get { | |
defer { semaphore.signal() } | |
semaphore.wait() | |
return value | |
} | |
_modify { | |
semaphore.wait() | |
yield &value | |
semaphore.signal() | |
} | |
} | |
public init(wrappedValue: T) { | |
self.value = wrappedValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment