Skip to content

Fix high CPU usage in callback thread due to incorrect timespec#782

Open
k1-801 wants to merge 1 commit intolibusb:connection-callbackfrom
k1-801:patch-1
Open

Fix high CPU usage in callback thread due to incorrect timespec#782
k1-801 wants to merge 1 commit intolibusb:connection-callbackfrom
k1-801:patch-1

Conversation

@k1-801
Copy link
Copy Markdown
Contributor

@k1-801 k1-801 commented Mar 29, 2026

@CalcProgrammer1 noticed high CPU usage (50%) on one of the threads when libusb backend is used for hotplug. It was determined that the load was caused by hidapi_thread_cond_timedwait(), which requires an absolute timespec, while the code passes a relative value. This patch copies how the structure is filled from the other place where hidapi_thread_cond_timedwait() is uses, which should fix the issue.

@mcuee mcuee added the libusb Related to libusb backend label Mar 29, 2026
@Youw Youw requested a review from Copilot March 29, 2026 17:29
/* 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);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd set it to 1 second - I've been using 1 second in multiple projects, and seems reasonable
5 second to exit the thread (effectively - to quit the application in some cases) seem a bit too much

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes high CPU usage in the libusb hotplug callback thread by passing an absolute timeout to hidapi_thread_cond_timedwait() (required by the pthread-backed implementation), instead of a relative timespec.

Changes:

  • Move timeout computation into the callback loop and build it as now + 5ms via hidapi_thread_gettime() + hidapi_thread_addtime().
  • Align the hotplug callback thread’s timed-wait behavior with the existing timed-wait usage elsewhere in libusb/hid.c.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

libusb Related to libusb backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants