diff --git a/Sources/OpenAI/OpenAI.swift b/Sources/OpenAI/OpenAI.swift index cfb1e9d1..182fced1 100644 --- a/Sources/OpenAI/OpenAI.swift +++ b/Sources/OpenAI/OpenAI.swift @@ -35,7 +35,7 @@ final public class OpenAI: OpenAIProtocol { } private let session: URLSessionProtocol - private var streamingSessions: [NSObject] = [] + private var streamingSessions = ArrayWithThreadSafety() public let configuration: Configuration diff --git a/Sources/OpenAI/Public/Utilities/ArrayWithThreadSafety.swift b/Sources/OpenAI/Public/Utilities/ArrayWithThreadSafety.swift new file mode 100644 index 00000000..a0c4db64 --- /dev/null +++ b/Sources/OpenAI/Public/Utilities/ArrayWithThreadSafety.swift @@ -0,0 +1,26 @@ +// +// ArrayWithThreadSafety.swift +// +// +// Created by James J Kalafus on 2024-02-01. +// + +import Foundation + +internal class ArrayWithThreadSafety { + private var array = [Element]() + private let queue = DispatchQueue(label: "us.kalaf.OpenAI.threadSafeArray", attributes: .concurrent) + + @inlinable public func append(_ element: Element) { + queue.async(flags: .barrier) { + self.array.append(element) + } + } + + @inlinable public func removeAll(where shouldBeRemoved: @escaping (Element) throws -> Bool) rethrows { + try queue.sync(flags: .barrier) { + try self.array.removeAll(where: shouldBeRemoved) + } + } +} +