Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions Sources/SendableProperty/SendableProperty.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,33 @@
// limitations under the License.
//===----------------------------------------------------------------------===//

// `Foundation` will be automatically imported with `SendableProperty`.
@_exported import Foundation
// `Synchronization` will be automatically imported with `SendableProperty`.
@_exported import Synchronization

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

/// A synchronization primitive that protects shared mutable state via mutual exclusion.
public final class Synchronized<T>: @unchecked Sendable {
private let lock = NSLock()
private var value: T
public final class Synchronized<T>: Sendable {
private let lock: Mutex<State>

private struct State: @unchecked Sendable {
var value: T
}

/// Creates a new instance.
/// - Parameter value: The initial value.
public init(_ value: T) {
self.value = value
self.lock = Mutex(State(value: value))
}

/// Calls the given closure after acquiring the lock and returns its value.
/// - Parameter body: The body of code to execute while the lock is held.
public func withLock<R>(_ body: (inout T) throws -> R) rethrows -> R {
lock.lock()
defer {
lock.unlock()
try lock.withLock { state in
try body(&state.value)
}
return try body(&value)
}
}