Skip to content

Commit

Permalink
Merge pull request #156 from kalafus/MacPaw.threadsafe
Browse files Browse the repository at this point in the history
array thread safety wrapper to fix racing condition causing Fatal error
  • Loading branch information
ingvarus-bc committed Feb 7, 2024
2 parents 27ad53b + e1b8728 commit 04ee92c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
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)
}
}
}

0 comments on commit 04ee92c

Please sign in to comment.