-
Notifications
You must be signed in to change notification settings - Fork 382
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #156 from kalafus/MacPaw.threadsafe
array thread safety wrapper to fix racing condition causing Fatal error
- Loading branch information
Showing
2 changed files
with
27 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 26 additions & 0 deletions
26
Sources/OpenAI/Public/Utilities/ArrayWithThreadSafety.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} | ||
|