Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

array thread safety wrapper to fix racing condition causing Fatal error #156

Merged
merged 1 commit into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/OpenAI/OpenAI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ final public class OpenAI: OpenAIProtocol {
}

private let session: URLSessionProtocol
private var streamingSessions: [NSObject] = []
private var streamingSessions = ArrayWithThreadSafety<NSObject>()

public let configuration: Configuration

Expand Down
26 changes: 26 additions & 0 deletions Sources/OpenAI/Public/Utilities/ArrayWithThreadSafety.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//
// ArrayWithThreadSafety.swift
//
//
// Created by James J Kalafus on 2024-02-01.
//

import Foundation

internal class ArrayWithThreadSafety<Element> {
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)
}
}
}

Loading