Skip to content

Commit ae78112

Browse files
committed
Fix crash caused by multithreading
1 parent 67bc014 commit ae78112

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

Sources/TaskStore/TaskStore.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ public class TaskStore<Key: Hashable> {
4646
/// - Parameter predicate: <#predicate description#>
4747
/// - Returns: <#description#>
4848
public func tasks(where predicate: (Key) -> Bool) -> [CancellableTask] {
49+
lock.lock(); defer { lock.unlock() }
4950
return taskMap
5051
.filter { key, _ in predicate(key) }
5152
.map(\.value)

Tests/TaskStoreTests/TaskStoreTests.swift

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,29 @@ import XCTest
33

44
final class TaskStoreTests: XCTestCase {
55

6+
func test_concurrentAccess() {
7+
let taskStore = TaskStore<String>()
8+
let task = Task {
9+
sleep(1)
10+
throw TestError.test
11+
}
12+
taskStore.setTask(task, forKey: "TestKey")
13+
14+
(1...100).forEach { _ in
15+
DispatchQueue.global().async {
16+
taskStore.setTask(task, forKey: "TestKey")
17+
_ = taskStore.task(forKey: "TestKey")
18+
}
19+
}
20+
21+
(1...100).forEach { _ in
22+
DispatchQueue.global().async {
23+
taskStore.setTask(task, forKey: "TestKey")
24+
_ = taskStore.tasks(where: { $0 == "TestKey" })
25+
}
26+
}
27+
}
28+
629
func test_subscript() {
730
let taskStore = TaskStore<Int>()
831
taskStore.setTask(
@@ -14,7 +37,7 @@ final class TaskStoreTests: XCTestCase {
1437
XCTAssertNotNil(taskStore[0])
1538
}
1639

17-
func test_searchTasks() {
40+
func test_searchTasksWithPredicate() {
1841
struct CustomKey: Hashable {
1942
let number: Int
2043
}

Tests/TaskStoreTests/TestError.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import Foundation
2+
3+
enum TestError: Error {
4+
case test
5+
}

0 commit comments

Comments
 (0)