Skip to content

Commit

Permalink
Use OSAllocatedUnfairLock on iOS 16+
Browse files Browse the repository at this point in the history
  • Loading branch information
dimitris-c committed Jul 11, 2024
1 parent 579fd26 commit 1916a06
Showing 1 changed file with 83 additions and 1 deletion.
84 changes: 83 additions & 1 deletion AudioStreaming/Core/Helpers/Lock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//

import Foundation
import os

protocol Lock {
func lock()
Expand All @@ -14,19 +15,100 @@ protocol Lock {

// Execute a closure while acquiring a lock
func withLock(body: () -> Void)

func deallocate()
}

/// A wrapper for `os_unfair_lock`
/// - Tag: UnfairLock
final class UnfairLock: Lock {
@usableFromInline let unfairLock: UnsafeMutablePointer<os_unfair_lock>

var unfairLock: Lock

init() {
if #available(iOS 16.0, *) {
unfairLock = OSStorageLock()
} else {
unfairLock = UnfairStorageLock()
}
}

deinit {
deallocate()
}

func deallocate() {
unfairLock.deallocate()
}

@inlinable
@inline(__always)
func withLock<Result>(body: () throws -> Result) rethrows -> Result {
try unfairLock.withLock(body: body)
}

@inlinable
@inline(__always)
func withLock(body: () -> Void) {
unfairLock.withLock(body: body)
}

@inlinable
@inline(__always)
func lock() {
unfairLock.lock()
}

@inlinable
@inline(__always)
func unlock() {
unfairLock.unlock()
}
}

@available(iOS 16.0, *)
private class OSStorageLock: Lock {
@usableFromInline
let osLock = OSAllocatedUnfairLock()

@inlinable
@inline(__always)
func lock() {
osLock.lock()
}

@inlinable
@inline(__always)
func unlock() {
osLock.unlock()
}

func withLock<Result>(body: () throws -> Result) rethrows -> Result {
try osLock.withLockUnchecked(body)
}

func withLock(body: () -> Void) {
osLock.withLockUnchecked(body)
}

func deallocate() {} // no-op
}

private class UnfairStorageLock: Lock {

@usableFromInline
let unfairLock: UnsafeMutablePointer<os_unfair_lock>

init() {
unfairLock = .allocate(capacity: 1)
unfairLock.initialize(to: os_unfair_lock())
}

deinit {
deallocate()
}

func deallocate() {
unfairLock.deallocate()
}

Expand Down

0 comments on commit 1916a06

Please sign in to comment.