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
30 changes: 17 additions & 13 deletions Sources/Support/CrossPlatformLock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,38 @@
//

import Foundation
#if canImport(os)
#if canImport(os) && os(macOS)
import os
#endif

/// A cross-platform thread-safe lock wrapper
public final class CrossPlatformLock<State: Sendable>: @unchecked Sendable {
#if canImport(os) && os(macOS)
private let lock: OSAllocatedUnfairLock<State>
#else

public init(initialState: State) {
self.lock = OSAllocatedUnfairLock(initialState: initialState)
}

public func withLock<T: Sendable>(_ operation: @Sendable (inout State) -> T) -> T {
lock.withLock(operation)
}
}

#else

/// A cross-platform thread-safe lock wrapper
public final class CrossPlatformLock<State: Sendable>: @unchecked Sendable {
private let nsLock = NSLock()
private var state: State
#endif

public init(initialState: State) {
#if canImport(os) && os(macOS)
self.lock = OSAllocatedUnfairLock(initialState: initialState)
#else
self.state = initialState
#endif
}

public func withLock<T: Sendable>(_ operation: @Sendable (inout State) -> T) -> T {
#if canImport(os) && os(macOS)
return lock.withLock(operation)
#else
nsLock.lock()
defer { nsLock.unlock() }
return operation(&state)
#endif
}
}

#endif