From e288ba118af7e7b147d6beaeb6267d3e2273ff46 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Sun, 29 Mar 2026 07:33:37 +0400 Subject: [PATCH 1/2] Fix high CPU usage in callback thread due to incorrect timespec --- libusb/hid.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/libusb/hid.c b/libusb/hid.c index ad0c4e87..5b7123a0 100644 --- a/libusb/hid.c +++ b/libusb/hid.c @@ -1215,16 +1215,16 @@ static void* callback_thread(void* user_data) { (void) user_data; - /* 5 msec timeout seems reasonable; don't set too low to avoid high CPU usage */ - /* This timeout only affects how much time it takes to stop the thread */ - hidapi_timespec ts; - ts.tv_sec = 0; - ts.tv_nsec = 5000000; - hidapi_thread_mutex_lock(&hid_hotplug_context.callback_thread); /* We stop the thread if by the moment there are no events left in the queue there are no callbacks left */ while (1) { + /* 5 msec timeout seems reasonable; don't set too low to avoid high CPU usage */ + /* This timeout only affects how much time it takes to stop the thread */ + hidapi_timespec ts; + hidapi_thread_gettime(&ts); + hidapi_thread_addtime(&ts, 5); + /* Make the tread fall asleep and wait for a condition to wake it up */ hidapi_thread_cond_timedwait(&hid_hotplug_context.callback_thread, &ts); From fa703283018a5a635efcf73bb1c6a0f036240919 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Mon, 30 Mar 2026 14:17:26 +0400 Subject: [PATCH 2/2] Update callback timeout --- libusb/hid.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libusb/hid.c b/libusb/hid.c index 5b7123a0..22a0b20d 100644 --- a/libusb/hid.c +++ b/libusb/hid.c @@ -1219,11 +1219,11 @@ static void* callback_thread(void* user_data) /* We stop the thread if by the moment there are no events left in the queue there are no callbacks left */ while (1) { - /* 5 msec timeout seems reasonable; don't set too low to avoid high CPU usage */ - /* This timeout only affects how much time it takes to stop the thread */ + /* Pretty much any value between 2 and 100 msec timeout seems reasonable; don't set too low to avoid high CPU usage */ + /* This timeout only affects how much time it takes to stop the thread if for any reason thread shutdown wasn't triggered by condition varaiable */ hidapi_timespec ts; hidapi_thread_gettime(&ts); - hidapi_thread_addtime(&ts, 5); + hidapi_thread_addtime(&ts, 100); /* Make the tread fall asleep and wait for a condition to wake it up */ hidapi_thread_cond_timedwait(&hid_hotplug_context.callback_thread, &ts);