Skip to content

Commit

Permalink
Fix not unlocking on ConcurrentDictionary subscript assign
Browse files Browse the repository at this point in the history
  • Loading branch information
Petr Prokop committed Dec 2, 2020
1 parent e44e54a commit a77aa03
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,4 @@ fastlane/test_output
# https://github.com/johnno1962/injectionforxcode

iOSInjectionProject/
.DS_Store
4 changes: 3 additions & 1 deletion SwiftConcurrentCollections/ConcurrentDictionary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,14 @@ public final class ConcurrentDictionary<Key: Hashable, Value> {
}
set {
rwlock.writeLock()
defer {
rwlock.unlock()
}
guard let newValue = newValue else {
_remove(key)
return
}
_set(value: newValue, forKey: key)
rwlock.unlock()
}
}

Expand Down
33 changes: 33 additions & 0 deletions SwiftConcurrentCollectionsTests/ConcurrentDictionaryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,38 @@ class ConcurrentDictionaryTests: XCTestCase {
XCTAssertEqual(concurrentDictionary[key], value * 2)
}

func testAssigningNilDoesUnlock() {
let concurrentDictionary = ConcurrentDictionary<String, Int>()
let key = "testKey"
let value = 999

concurrentDictionary[key] = value

let queue = DispatchQueue(
label: "ThreadSafeDictionaryTests.queue",
qos: .userInteractive,
attributes: []
)

let expectationOne = expectation(description: "Assigning `nil` first time")
let expectationTwo = expectation(description: "Assigning `nil` second time")

queue.async {
concurrentDictionary[key] = nil
expectationOne.fulfill()
}

queue.sync {
concurrentDictionary[key] = nil
expectationTwo.fulfill()
}

waitForExpectations(timeout: 1, handler: nil)

concurrentDictionary[key] = value
XCTAssertEqual(concurrentDictionary[key], value)
}

}


0 comments on commit a77aa03

Please sign in to comment.