Swiftpack.co - Package - shareup/synchronized

synchronized

Synchronized provides a simple Swift-y implementation of a lock and a recursive lock. Lock wraps os_unfair_lock. RecursiveLock wraps pthread_mutex_t. Synchronized's API is designed for convenience and simplicity.

The two lock's APIs are identical and limited to two public methods: func locked<T>(_ block: () throws -> T) rethrows -> T and func tryLocked(_ block: () throws -> Void) rethrows. locked() blocks on contention and then executes the supplied closure, returning or throwing the closure's return value or thrown error. tryLocked() attemps to acquire the lock. If the lock can be acquired, the supplied closure is executed and true is returned. If the lock cannot be acquired, the closure is not executed and false is returned.

@synchonized replacement

Synchronized started life as a simple (and simplified) re-implmentation of Objective-C's @synchronized for Swift. If you're interested in that version, you should look at v1.2.1.

Usage

let lock = Lock()
let lockInput: Int = 0
let lockOutput = lock.locked { lockInput + 1 }
XCTAssertEqual(1, lockOutput)

let recursiveLock = RecursiveLock()
let recursiveLockInput: Int = 0
let recursiveLockOutput = recursiveLock.locked { recursiveLockInput + 1 }
XCTAssertEqual(1, recursiveLockOutput)

Installation

Swift Package Manager

To use Synchronized with the Swift Package Manager, add a dependency to your Package.swift file:

let package = Package(
  dependencies: [
    .package(url: "https://github.com/shareup/synchronized.git", .upToNextMajor(from: "2.1.0"))
  ]
)

Linux is not currently supported

Github

link
Stars: 1

Dependencies

Releases

2.1.0 -

Changes tryLocked() to return Bool from to indicate success or failure of acquiring the lock.

2.0.0 -

Removes the Synchronized protocol in favor of directly exposing Lock and RecusiveLock for use by client.

1.2.1 -

Reduce lock contention when cleaning up locks for deallocated objects.

1.1.1 -

Add missing tests to allTests.

1.1.0 -

Adds support for returning values from synchronized() and sync() and for throwing in those functions.

1.0.0 -

Initial release of Synchronized