Skip to content

Mutex should be ~Copyable #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
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
6 changes: 3 additions & 3 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ jobs:

linux_swift_6_1:
runs-on: ubuntu-latest
container: swift:6.1
container: swift:6.1.2
steps:
- name: Checkout
uses: actions/checkout@v4
Expand Down Expand Up @@ -123,7 +123,7 @@ jobs:

linux_swift_6_1_musl:
runs-on: ubuntu-latest
container: swift:6.1
container: swift:6.1.2
steps:
- name: Checkout
uses: actions/checkout@v4
Expand All @@ -146,7 +146,7 @@ jobs:
- name: Install Swift
uses: SwiftyLab/setup-swift@latest
with:
swift-version: "6.1.0"
swift-version: "6.1.2"
- name: Version
run: swift --version
- name: Build
Expand Down
1 change: 1 addition & 0 deletions Sources/AllocatedLock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
//

// Backports the Swift interface around OSAllocatedUnfairLock available in recent Darwin platforms
@available(*, deprecated, message: "Unused by Mutex and will be removed in future versions.")
public struct AllocatedLock<State>: @unchecked Sendable {

@usableFromInline
Expand Down
211 changes: 155 additions & 56 deletions Sources/Mutex.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,82 +29,181 @@
// SOFTWARE.
//

#if compiler(>=6)

#if !canImport(WinSDK)

// Backports the Swift 6 type Mutex<Value> to all Darwin platforms

// @available(macOS, deprecated: 15.0, message: "use Mutex from Synchronization module included with Swift 6")
// @available(iOS, deprecated: 18.0, message: "use Mutex from Synchronization module included with Swift 6")
// @available(tvOS, deprecated: 18.0, message: "use Mutex from Synchronization module included with Swift 6")
// @available(watchOS, deprecated: 11.0, message: "use Mutex from Synchronization module included with Swift 6")
// @available(visionOS, deprecated: 2.0, message: "use Mutex from Synchronization module included with Swift 6")
public struct Mutex<Value>: Sendable {
let lock: AllocatedLock<Value> // Compatible with OSAllocatedUnfairLock iOS 16+
@available(macOS, introduced: 13.0, deprecated: 15.0, message: "use Mutex from Synchronization module")
@available(iOS, introduced: 16.0, deprecated: 18.0, message: "use Mutex from Synchronization module")
@available(tvOS, introduced: 18.0, deprecated: 15.0, message: "use Mutex from Synchronization module")
@available(watchOS, introduced: 11.0, deprecated: 15.0, message: "use Mutex from Synchronization module")
@available(visionOS, introduced: 2.0, deprecated: 15.0, message: "use Mutex from Synchronization module")
public struct Mutex<Value: ~Copyable>: @unchecked Sendable, ~Copyable {
let storage: Storage<Value>

public init(_ initialValue: consuming sending Value) {
self.storage = Storage(initialValue)
}

public borrowing func withLock<Result, E: Error>(
_ body: (inout sending Value) throws(E) -> sending Result
) throws(E) -> sending Result {
storage.lock()
defer { storage.unlock() }
return try body(&storage.value)
}

public borrowing func withLockIfAvailable<Result, E: Error>(
_ body: (inout sending Value) throws(E) -> sending Result
) throws(E) -> sending Result? {
guard storage.tryLock() else { return nil }
defer { storage.unlock() }
return try body(&storage.value)
}
}

#if compiler(>=6)
public extension Mutex {
init(_ initialValue: consuming sending Value) {
self.lock = AllocatedLock(uncheckedState: initialValue)
#else

// Windows doesn't support ~Copyable yet

public struct Mutex<Value>: @unchecked Sendable {
let storage: Storage<Value>

public init(_ initialValue: consuming sending Value) {
self.storage = Storage(initialValue)
}

borrowing func withLock<Result, E: Error>(
public borrowing func withLock<Result, E: Error>(
_ body: (inout sending Value) throws(E) -> sending Result
) throws(E) -> sending Result {
do {
return try lock.withLockUnchecked { value in
nonisolated(unsafe) var copy = value
defer { value = copy }
return try Transferring(body(&copy))
}.value
} catch let error as E {
throw error
} catch {
preconditionFailure("cannot occur")
}
}

borrowing func withLockIfAvailable<Result, E>(
storage.lock()
defer { storage.unlock() }
return try body(&storage.value)
}

public borrowing func withLockIfAvailable<Result, E: Error>(
_ body: (inout sending Value) throws(E) -> sending Result
) throws(E) -> sending Result? where E: Error {
do {
return try lock.withLockIfAvailableUnchecked { value in
nonisolated(unsafe) var copy = value
defer { value = copy }
return try Transferring(body(&copy))
}?.value
} catch let error as E {
throw error
} catch {
preconditionFailure("cannot occur")
}
) throws(E) -> sending Result? {
guard storage.tryLock() else { return nil }
defer { storage.unlock() }
return try body(&storage.value)
}
}
private struct Transferring<T> {
nonisolated(unsafe) var value: T

init(_ value: T) {
self.value = value
#endif

#if canImport(Darwin)

import struct os.os_unfair_lock_t
import struct os.os_unfair_lock
import func os.os_unfair_lock_lock
import func os.os_unfair_lock_unlock
import func os.os_unfair_lock_trylock

final class Storage<Value: ~Copyable> {
private let _lock: os_unfair_lock_t
var value: Value

init(_ initialValue: consuming Value) {
self._lock = .allocate(capacity: 1)
self._lock.initialize(to: os_unfair_lock())
self.value = initialValue
}

func lock() {
os_unfair_lock_lock(_lock)
}

func unlock() {
os_unfair_lock_unlock(_lock)
}

func tryLock() -> Bool {
os_unfair_lock_trylock(_lock)
}

deinit {
self._lock.deinitialize(count: 1)
self._lock.deallocate()
}
}

#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)

#if canImport(Musl)
import Musl
#elseif canImport(Bionic)
import Android
#else
public extension Mutex {
import Glibc
#endif

final class Storage<Value: ~Copyable> {
private let _lock: UnsafeMutablePointer<pthread_mutex_t>

var value: Value

init(_ initialValue: consuming Value) {
self.lock = AllocatedLock(uncheckedState: initialValue)
var attr = pthread_mutexattr_t()
pthread_mutexattr_init(&attr)
self._lock = .allocate(capacity: 1)
let err = pthread_mutex_init(self._lock, &attr)
precondition(err == 0, "pthread_mutex_init error: \(err)")
self.value = initialValue
}

func lock() {
let err = pthread_mutex_lock(_lock)
precondition(err == 0, "pthread_mutex_lock error: \(err)")
}

borrowing func withLock<Result>(
_ body: (inout Value) throws -> Result
) rethrows -> Result {
try lock.withLockUnchecked {
return try body(&$0)
}
func unlock() {
let err = pthread_mutex_unlock(_lock)
precondition(err == 0, "pthread_mutex_unlock error: \(err)")
}

borrowing func withLockIfAvailable<Result>(
_ body: (inout Value) throws -> Result
) rethrows -> Result? {
try lock.withLockIfAvailableUnchecked {
return try body(&$0)
}
func tryLock() -> Bool {
pthread_mutex_trylock(_lock) == 0
}

deinit {
let err = pthread_mutex_destroy(self._lock)
precondition(err == 0, "pthread_mutex_destroy error: \(err)")
self._lock.deallocate()
}
}

#elseif canImport(WinSDK)

import ucrt
import WinSDK

final class Storage<Value> {
private let _lock: UnsafeMutablePointer<SRWLOCK>

var value: Value

init(_ initialValue: Value) {
self._lock = .allocate(capacity: 1)
InitializeSRWLock(self._lock)
self.value = initialValue
}

func lock() {
AcquireSRWLockExclusive(_lock)
}

func unlock() {
ReleaseSRWLockExclusive(_lock)
}

func tryLock() -> Bool {
TryAcquireSRWLockExclusive(_lock) != 0
}
}

#endif

#endif
Loading
Loading