Digital PCT265 story ONEAPP-7249 - Better once implementation to avoid mutex lockups.

This commit is contained in:
Hedden, Kyle Matthew 2024-04-29 15:20:09 -04:00
parent b6a51ebb9c
commit f7af3e52f1

View File

@ -8,7 +8,7 @@
import Foundation import Foundation
extension DispatchQueue { extension DispatchQueue {
private static var _onceTracker = [String]() private static var _onceTracker = Set<String>()
public class func once( public class func once(
file: String = #file, file: String = #file,
@ -31,12 +31,17 @@ extension DispatchQueue {
token: String, token: String,
block: () -> Void block: () -> Void
) { ) {
// Peek ahead to avoid the intersection.
guard !_onceTracker.contains(token) else { return }
objc_sync_enter(self) objc_sync_enter(self)
defer { objc_sync_exit(self) } defer { objc_sync_exit(self) }
// Double check we are the first in the critical section.
guard !_onceTracker.contains(token) else { return } guard !_onceTracker.contains(token) else { return }
_onceTracker.append(token) // Execute.
_onceTracker.insert(token)
block() block()
} }
} }