Skip to content

Commit 969703d

Browse files
authored
Replace NSLock with Mutex (#193)
This PR replaces `NSLock` with `Mutex`. Thanks @dcantah for the idea!
1 parent 9775528 commit 969703d

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

Sources/SendableProperty/SendableProperty.swift

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,32 +14,33 @@
1414
// limitations under the License.
1515
//===----------------------------------------------------------------------===//
1616

17-
// `Foundation` will be automatically imported with `SendableProperty`.
18-
@_exported import Foundation
17+
// `Synchronization` will be automatically imported with `SendableProperty`.
18+
@_exported import Synchronization
1919

2020
// A declaration of the `@SendableProperty` macro.
2121
@attached(peer, names: arbitrary)
2222
@attached(accessor)
2323
public macro SendableProperty() = #externalMacro(module: "SendablePropertyMacros", type: "SendablePropertyMacro")
2424

2525
/// A synchronization primitive that protects shared mutable state via mutual exclusion.
26-
public final class Synchronized<T>: @unchecked Sendable {
27-
private let lock = NSLock()
28-
private var value: T
26+
public final class Synchronized<T>: Sendable {
27+
private let lock: Mutex<State>
28+
29+
private struct State: @unchecked Sendable {
30+
var value: T
31+
}
2932

3033
/// Creates a new instance.
3134
/// - Parameter value: The initial value.
3235
public init(_ value: T) {
33-
self.value = value
36+
self.lock = Mutex(State(value: value))
3437
}
3538

3639
/// Calls the given closure after acquiring the lock and returns its value.
3740
/// - Parameter body: The body of code to execute while the lock is held.
3841
public func withLock<R>(_ body: (inout T) throws -> R) rethrows -> R {
39-
lock.lock()
40-
defer {
41-
lock.unlock()
42+
try lock.withLock { state in
43+
try body(&state.value)
4244
}
43-
return try body(&value)
4445
}
4546
}

0 commit comments

Comments
 (0)