haimgel / display-switch

Turn a $30 USB switch into a full-featured multi-monitor KVM switch
https://haim.dev/posts/2020-07-28-dual-monitor-kvm/
MIT License
2.82k stars 110 forks source link

100% CPU usage on Linux #110

Closed jabl closed 1 year ago

jabl commented 1 year ago

Hi,

I recently updated to the latest version of display-switch (commit e2e8be35a196152e301ddf726cb95de0ff2b3ef6) and I discovered that display_switch is now pegging a cpu core when running. I tried to track down what was happening with callgrind, and it seems it's calling src/platform/pnp_detect_libusb.rs:context.handle_events(None) in a tight loop. The following fixes the CPU pegging, but adding a sleep is obviously not a correct solution, but just to demonstrate the problem:

index 8da2108..9639c8a 100644
--- a/src/platform/pnp_detect_libusb.rs
+++ b/src/platform/pnp_detect_libusb.rs
@@ -6,6 +6,8 @@
 use crate::usb::{device2str, UsbCallback};
 use anyhow::{anyhow, Result};
 use rusb::{Context, Device, UsbContext};
+use std::{thread, time::Duration};
+

 /// Detection of plugged in / removed USB devices: uses "libusb" and should work on Linux
 /// and MacOS, but not on Windows: libusb does not support hotplug on Windows.
@@ -40,6 +42,7 @@ impl PnPDetectLibusb {
                 if let Err(err) = context.handle_events(None) {
                     error!("Error during USB errors handling: {:?}", err)
                 };
+               thread::sleep(Duration::from_millis(100));
             }
         } else {
             // This should never happen: hotplug is supported on Linux and MacOS both.
haimgel commented 1 year ago

111 should have resolved this.