haimgel/display-switch

100% CPU usage on Linux

jabl opened this issue · 1 comments

jabl commented

Hi,

I recently updated to the latest version of display-switch (commit e2e8be3) 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.

#111 should have resolved this.