Skip to content

Instantly share code, notes, and snippets.

@LK-Simon
Last active July 13, 2022 10:51
Show Gist options
  • Save LK-Simon/9da3d4238678f5c3a4702fc416c93f87 to your computer and use it in GitHub Desktop.
Save LK-Simon/9da3d4238678f5c3a4702fc416c93f87 to your computer and use it in GitHub Desktop.
Swift Property Wrapper to make a Var Thread-Safe using an enforced Semaphore Lock
import Foundation
@propertyWrapper
public struct ThreadSafe<T> {
public var lock = DispatchSemaphore(value: 1)
private var value: T
public var wrappedValue: T {
get {
lock.wait()
let result = value
lock.signal()
return result
}
set {
lock.wait()
value = newValue
lock.signal()
}
}
public init(wrappedValue: T) {
lock.wait()
value = wrappedValue
lock.signal()
}
}
@LK-Simon
Copy link
Author

OBSOLITE!

Use instead my Swift Package, which you can find with full instructions here: https://github.com/Flowduino/ThreadSafeSwift/

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