Skip to content

Commit 04ee92c

Browse files
authored
Merge pull request #156 from kalafus/MacPaw.threadsafe
array thread safety wrapper to fix racing condition causing Fatal error
2 parents 27ad53b + e1b8728 commit 04ee92c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

Sources/OpenAI/OpenAI.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ final public class OpenAI: OpenAIProtocol {
3535
}
3636

3737
private let session: URLSessionProtocol
38-
private var streamingSessions: [NSObject] = []
38+
private var streamingSessions = ArrayWithThreadSafety<NSObject>()
3939

4040
public let configuration: Configuration
4141

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
//
2+
// ArrayWithThreadSafety.swift
3+
//
4+
//
5+
// Created by James J Kalafus on 2024-02-01.
6+
//
7+
8+
import Foundation
9+
10+
internal class ArrayWithThreadSafety<Element> {
11+
private var array = [Element]()
12+
private let queue = DispatchQueue(label: "us.kalaf.OpenAI.threadSafeArray", attributes: .concurrent)
13+
14+
@inlinable public func append(_ element: Element) {
15+
queue.async(flags: .barrier) {
16+
self.array.append(element)
17+
}
18+
}
19+
20+
@inlinable public func removeAll(where shouldBeRemoved: @escaping (Element) throws -> Bool) rethrows {
21+
try queue.sync(flags: .barrier) {
22+
try self.array.removeAll(where: shouldBeRemoved)
23+
}
24+
}
25+
}
26+

0 commit comments

Comments
 (0)