Replace busy-wait hotkey listener with efficient event-driven approach

This commit is contained in:
2025-05-11 18:21:50 -05:00
parent 0e6841bd8a
commit 34b0d700a6
+32 -10
View File
@@ -463,8 +463,37 @@ fn setup_hotkeys(shared_state: Arc<Mutex<SharedState>>) -> Option<GlobalHotKeyMa
let _manager_ref = &manager_for_thread;
println!("Hotkey manager reference maintained in thread");
// Create a channel to signal thread termination
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
// Spawn a thread to monitor the running flag
let monitor_state = state_clone.clone();
thread::spawn(move || {
loop {
match event_receiver.try_recv() {
// Check if we should exit
if let Ok(state) = monitor_state.lock() {
if !state.running {
println!("Monitor thread detected running=false, signaling hotkey thread to exit");
let _ = exit_tx.send(());
break;
}
}
// Sleep briefly to avoid high CPU usage
std::thread::sleep(Duration::from_millis(100));
}
});
// Main event loop - efficiently wait for events using blocking recv()
loop {
// Use std::sync::mpsc::TryRecv to check if we should exit without blocking
if exit_rx.try_recv().is_ok() {
println!("Hotkey listener received exit signal, terminating thread");
break;
}
// Use blocking recv() with a timeout to efficiently wait for events
// This avoids busy-waiting and reduces CPU usage to near 0% when idle
match event_receiver.recv_timeout(Duration::from_millis(500)) {
Ok(event) => {
println!("Received hotkey event: {:?}", event);
if event.state == HotKeyState::Pressed {
@@ -493,15 +522,8 @@ fn setup_hotkeys(shared_state: Arc<Mutex<SharedState>>) -> Option<GlobalHotKeyMa
}
},
Err(_) => {
// No events or channel disconnected, sleep briefly
std::thread::sleep(Duration::from_millis(50));
}
}
// Check shared state running flag
if let Ok(state) = state_clone.lock() {
if !state.running {
println!("Hotkey listener detected running=false, exiting thread.");
break;
// Timeout or channel disconnected, just continue the loop
// No need to sleep as recv_timeout already waited
}
}
}