Skip to content

Commit d05582a

Browse files
committed
(fix) resolve concurrency race condition
1 parent 46b4676 commit d05582a

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

AXSwiftObserverExample/AppDelegate.swift

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,23 @@ class AppDelegate: NSObject, NSApplicationDelegate {
2121
}
2222
}
2323

24+
private class Sendly<T>: @unchecked Sendable {
25+
private let lock = NSLock()
26+
private var _value: T
27+
var value: T {
28+
get { lock.withLock { _value } }
29+
set { lock.withLock { _value = newValue } }
30+
}
31+
32+
init(_ value: T) {
33+
lock.lock()
34+
defer { lock.unlock() }
35+
self._value = value
36+
}
37+
}
38+
2439
func startWatcher(_ app: Application) throws {
25-
var updated = false
40+
let updated = Sendly(false)
2641
observer = app.createObserver { (observer: Observer, element: UIElement, event: UIElement.AXNotification, info: [String: AnyObject]?) in
2742
var elementDesc: String!
2843
if let role = try? element.role()!, role == .window {
@@ -43,12 +58,12 @@ class AppDelegate: NSObject, NSApplicationDelegate {
4358
}
4459

4560
// Group simultaneous events together with --- lines
46-
if !updated {
47-
updated = true
61+
if !updated.value {
62+
updated.value = true
4863
// Set this code to run after the current run loop, which is dispatching all notifications.
4964
DispatchQueue.main.async {
5065
print("---")
51-
updated = false
66+
updated.value = false
5267
}
5368
}
5469
}

0 commit comments

Comments
 (0)