Created
July 19, 2025 22:46
-
-
Save timboudreau/945062f6354caff1d8d2e02b7d9a2280 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| private final class DelayedRegistration : Sendable { | |
| static let singleton = DelayedRegistration() | |
| private let queue : TreiberishStack<DREntry> = .init() | |
| private let enqueued = ManagedAtomic(false) | |
| struct DREntry : @unchecked Sendable { | |
| weak var stub : FolderMonitorStub? | |
| weak var monitor : (any ChangeMonitor)? | |
| func withValues(_ f : (FolderMonitorStub, any ChangeMonitor) -> Void) -> Bool { | |
| if let s = stub, let m = monitor { | |
| f(s, m) | |
| return true | |
| } | |
| return false | |
| } | |
| } | |
| func push(stub : FolderMonitorStub, monitor: any ChangeMonitor){ | |
| queue.push(DREntry(stub: stub, monitor: monitor)) | |
| if enqueued.compareExchange(expected: false, desired: true, ordering: .acquiringAndReleasing).exchanged { | |
| DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime.now() + 4, execute: self.process) | |
| } | |
| } | |
| private func process() { | |
| defer { enqueued.store(false, ordering: .sequentiallyConsistent)} | |
| var count = 0 | |
| var dead = 0 | |
| while !queue.isEmpty { | |
| for entry in queue.drain() { | |
| let registered = entry.withValues { stub, monitor in | |
| // XXX we may want to track if the explict deregister method was called, and if so, | |
| // skip this | |
| stub.reallyRegister(callback: monitor) | |
| } | |
| if registered { | |
| count += 1 | |
| } else { | |
| dead += 1 | |
| } | |
| } | |
| } | |
| print("Delayed monitor registration \(count) registered, \(dead) dead") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment