Skip to content
Closed
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
2 changes: 1 addition & 1 deletion Sources/ComposableArchitecture/Effects/Cancellation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,4 @@ extension Effect {
}

var cancellationCancellables: [AnyHashable: Set<AnyDisposable>] = [:]
let cancellablesLock = NSRecursiveLock()
let cancellablesLock = Lock.PthreadLock(recursive: true)
113 changes: 112 additions & 1 deletion Sources/ComposableArchitecture/Internal/Locking.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,118 @@ import Foundation
}
#endif

extension NSRecursiveLock {
/// `Lock` exposes `os_unfair_lock` on supported platforms, with pthread mutex as the
/// fallback.
/// Implementation copied from https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/Atomic.swift
internal class Lock {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@available(iOS 10.0, *)
@available(macOS 10.12, *)
@available(tvOS 10.0, *)
@available(watchOS 3.0, *)
internal final class UnfairLock: Lock {
private let _lock: os_unfair_lock_t

override init() {
_lock = .allocate(capacity: 1)
_lock.initialize(to: os_unfair_lock())
super.init()
}

override func lock() {
os_unfair_lock_lock(_lock)
}

override func unlock() {
os_unfair_lock_unlock(_lock)
}

override func `try`() -> Bool {
return os_unfair_lock_trylock(_lock)
}

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

internal final class PthreadLock: Lock {
private let _lock: UnsafeMutablePointer<pthread_mutex_t>

init(recursive: Bool = false) {
_lock = .allocate(capacity: 1)
_lock.initialize(to: pthread_mutex_t())

let attr = UnsafeMutablePointer<pthread_mutexattr_t>.allocate(capacity: 1)
attr.initialize(to: pthread_mutexattr_t())
pthread_mutexattr_init(attr)

defer {
pthread_mutexattr_destroy(attr)
attr.deinitialize(count: 1)
attr.deallocate()
}

pthread_mutexattr_settype(attr, Int32(recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_ERRORCHECK))

let status = pthread_mutex_init(_lock, attr)
assert(status == 0, "Unexpected pthread mutex error code: \(status)")

super.init()
}

override func lock() {
let status = pthread_mutex_lock(_lock)
assert(status == 0, "Unexpected pthread mutex error code: \(status)")
}

override func unlock() {
let status = pthread_mutex_unlock(_lock)
assert(status == 0, "Unexpected pthread mutex error code: \(status)")
}

override func `try`() -> Bool {
let status = pthread_mutex_trylock(_lock)
switch status {
case 0:
return true
case EBUSY, EAGAIN, EDEADLK:
return false
default:
assertionFailure("Unexpected pthread mutex error code: \(status)")
return false
}
}

deinit {
let status = pthread_mutex_destroy(_lock)
assert(status == 0, "Unexpected pthread mutex error code: \(status)")

_lock.deinitialize(count: 1)
_lock.deallocate()
}
}

static func make() -> Lock {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
if #available(*, iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0) {
return UnfairLock()
}
#endif

return PthreadLock()
}

private init() {}

func lock() { fatalError() }
func unlock() { fatalError() }
func `try`() -> Bool { fatalError() }
}

extension Lock.PthreadLock {
@inlinable @discardableResult
func sync<R>(work: () -> R) -> R {
self.lock()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import Foundation
import ReactiveSwift

extension Signal.Observer {
internal convenience init(mappingInterruptedToCompleted observer: Signal<Value, Error>.Observer) {
self.init { event in
switch event {
case .value, .completed, .failed:
observer.send(event)
case .interrupted:
observer.sendCompleted()
}
}
}
}

@propertyWrapper
internal final class RecursiveMutableProperty<Value> {
private let lock: Lock.PthreadLock

private let token: Lifetime.Token
private let observer: Signal<Value, Never>.Observer

private var currentValue: Value

/// The current value of the property.
///
/// Setting this to a new value will notify all observers of `signal`, or
/// signals created using `producer`.
public var value: Value {
get {
lock.lock()
defer { lock.unlock() }
return currentValue

}
set {
lock.lock()
currentValue = newValue
lock.unlock()

observer.send(value: newValue)
}
}

@inlinable
public var wrappedValue: Value {
get { value }
set { value = newValue }
}

@inlinable
public var projectedValue: RecursiveMutableProperty<Value> {
return self
}


/// The lifetime of the property.
public let lifetime: Lifetime

/// A signal that will send the property's changes over time,
/// then complete when the property has deinitialized.
public let signal: Signal<Value, Never>

/// A producer for Signals that will send the property's current value,
/// followed by all changes over time, then complete when the property has
/// deinitialized.
public var producer: SignalProducer<Value, Never> {
return SignalProducer { [signal, value] observer, lifetime in
let _value: Value
_value = value

observer.send(value: _value)
lifetime += signal.observe(Signal.Observer(mappingInterruptedToCompleted: observer))
}
}


public init(_ initialValue: Value) {
(signal, observer) = Signal.pipe()
(lifetime, token) = Lifetime.make()

lock = Lock.PthreadLock(recursive: true)
currentValue = initialValue
}

/// Initializes a mutable property that first takes on `initialValue`
///
/// - parameters:
/// - initialValue: Starting value for the mutable property.
public convenience init(wrappedValue: Value) {
self.init(wrappedValue)
}
}
2 changes: 1 addition & 1 deletion Sources/ComposableArchitecture/Store.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import ReactiveSwift
/// You will typically construct a single one of these at the root of your application, and then use
/// the `scope` method to derive more focused stores that can be passed to subviews.
public final class Store<State, Action> {
@MutableProperty
@RecursiveMutableProperty
private(set) var state: State

private var isSending = false
Expand Down