Skip to content

Commit

Permalink
Merge pull request #43 from 4brunu/feature/avoid-deadlock
Browse files Browse the repository at this point in the history
Avoid deadlock by using NSRecursiveLock
  • Loading branch information
roberthein authored Feb 21, 2020
2 parents e6eef7d + c6d71a7 commit dfbfa39
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 16 deletions.
16 changes: 1 addition & 15 deletions Observable/Classes/Lock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,4 @@ internal protocol Lock {
func unlock()
}

internal final class Mutex: Lock {
private var mutex: pthread_mutex_t = {
var mutex = pthread_mutex_t()
pthread_mutex_init(&mutex, nil)
return mutex
}()

func lock() {
pthread_mutex_lock(&mutex)
}

func unlock() {
pthread_mutex_unlock(&mutex)
}
}
extension NSRecursiveLock: Lock {}
2 changes: 1 addition & 1 deletion Observable/Classes/Observable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class Observable<T> {
private var observers: [Int: (Observer, DispatchQueue?)] = [:]
private var uniqueID = (0...).makeIterator()

fileprivate let lock: Lock = Mutex()
fileprivate let lock: Lock = NSRecursiveLock()

fileprivate var _value: T {
didSet {
Expand Down
19 changes: 19 additions & 0 deletions Observable/Tests/Observable_Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,25 @@ class Observable_Tests: XCTestCase {
XCTAssert(true)
}

func test_whenUpdatingValueFromObserver_shouldNotDeadLock() {
let exp = expectation(description: "")
exp.expectedFulfillmentCount = 4
let observable = MutableObservable(0)
var lastValueResult: Int?

observable.observe { newValue, _ in
lastValueResult = newValue
exp.fulfill()
if newValue < 3 {
observable.wrappedValue = newValue + 1
}
}.add(to: &disposal)

wait(for: [exp], timeout: 1.0)
XCTAssertEqual(lastValueResult, 3)
XCTAssert(true)
}

// MARK: - Using Singleton
func test_whenUsingDispatchMain_shouldSucceed() {
let exp = expectation(description: "")
Expand Down

0 comments on commit dfbfa39

Please sign in to comment.