summaryrefslogtreecommitdiff
path: root/libusb/os
diff options
context:
space:
mode:
authorChris Dickens <christopher.a.dickens@gmail.com>2020-01-24 11:51:55 -0800
committerChris Dickens <christopher.a.dickens@gmail.com>2020-02-07 15:56:05 -0800
commita5f6a43342d6bd0da57092ec4e1a6bce30bb2bce (patch)
treefcff5e76bddf71a765bfd66c44c96e6e102019ba /libusb/os
parent9c28ad219b654011783a42ec888ca87dbda704a6 (diff)
downloadlibusb-a5f6a43342d6bd0da57092ec4e1a6bce30bb2bce.tar.gz
threads_posix: Use thread-local storage to cache thread ID
Trying to capture debug logs that reproduce a problem can be tricky. Turning up the debug level will automatically make the program a bit slower. This alone cane make timing-sensitive bugs "disappear" when capturing logs. One of the hot paths for debug messages is fetching the thread ID, which is immeasurably helpful in understanding thread interactions within the library. Unfortunately most implementations require a system call to fetch the executing thread's ID, which isn't exactly going to help in the way of execution time. Add a check for thread-local storage support when configuring the library to build. If the toolchain provides this support, only one system call will be required per thread. This check is only done for non-Windows systems because thread-local storage is inefficiently implemented on MinGW. Closes #682 Signed-off-by: Chris Dickens <christopher.a.dickens@gmail.com>
Diffstat (limited to 'libusb/os')
-rw-r--r--libusb/os/threads_posix.c24
1 files changed, 16 insertions, 8 deletions
diff --git a/libusb/os/threads_posix.c b/libusb/os/threads_posix.c
index 92bb11d..76384ac 100644
--- a/libusb/os/threads_posix.c
+++ b/libusb/os/threads_posix.c
@@ -52,22 +52,30 @@ int usbi_cond_timedwait(pthread_cond_t *cond,
int usbi_get_tid(void)
{
- int ret;
+#ifdef HAVE_CC_THREAD_LOCAL
+ static _Thread_local int tid;
+
+ if (tid)
+ return tid;
+#else
+ int tid;
+#endif
+
#if defined(__ANDROID__)
- ret = gettid();
+ tid = gettid();
#elif defined(__linux__)
- ret = syscall(SYS_gettid);
+ tid = syscall(SYS_gettid);
#elif defined(__OpenBSD__)
/* The following only works with OpenBSD > 5.1 as it requires
real thread support. For 5.1 and earlier, -1 is returned. */
- ret = syscall(SYS_getthrid);
+ tid = syscall(SYS_getthrid);
#elif defined(__APPLE__)
- ret = (int)pthread_mach_thread_np(pthread_self());
+ tid = (int)pthread_mach_thread_np(pthread_self());
#elif defined(__CYGWIN__)
- ret = GetCurrentThreadId();
+ tid = GetCurrentThreadId();
#else
- ret = -1;
+ tid = -1;
#endif
/* TODO: NetBSD thread ID support */
- return ret;
+ return tid;
}