Skip to content

Cross platform lock backporting the Swift 6 Mutex API to earlier platforms

License

Notifications You must be signed in to change notification settings

swhitty/swift-mutex

Repository files navigation

Build Codecov Platforms Swift 5.10 License Twitter

Introduction

swift-mutex is a cross platform lock backporting the Swift 6 Mutex API to Swift 5.9 and all Darwin platforms.

Mutex is built upon AllocatedLock, a cross platform lock with an API compatible with OSAllocatedUnfairLock. The lock wraps os_unfair_lock_t on Darwin platforms, pthread_mutex_t on Linux and SRWLOCK on Windows.

Installation

The package can be installed by using Swift Package Manager.

Note: Mutex requires Swift 5.9 on Xcode 15+. It runs on iOS 13+, tvOS 13+, macOS 10.15+, Linux and Windows. To install using Swift Package Manager, add this to the dependencies: section in your Package.swift file:

.package(url: "https://github.com/swhitty/swift-mutex.git", .upToNextMajor(from: "0.0.5"))

Usage

Usage is similar to the Swift 6 Mutex

let state = Mutex<Int>(0)

Use .withLock to acquire the lock to read the state:

let val = state.withLock { $0 }

Or mutate the state

let val = state.withLock { $0 += 1 }

Gist

A simpler, single file version compatible with macOS 13 / iOS 16 can be found in this gist.

Credits

swift-mutex is primarily the work of Simon Whitty.

(Full list of contributors)