2 * libusb synchronization using POSIX Threads
4 * Copyright © 2011 Vitali Lovich <vlovich@aliph.com>
5 * Copyright © 2011 Peter Stuge <peter@stuge.se>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #if defined(__ANDROID__)
27 #elif defined(__HAIKU__)
28 # include <os/kernel/OS.h>
29 #elif defined(__linux__)
30 # include <sys/syscall.h>
32 #elif defined(__NetBSD__)
34 #elif defined(__OpenBSD__)
36 # include <sys/syscall.h>
38 #elif defined(__sun__)
42 void usbi_cond_init(pthread_cond_t *cond)
44 #ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
45 pthread_condattr_t condattr;
47 PTHREAD_CHECK(pthread_condattr_init(&condattr));
48 PTHREAD_CHECK(pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC));
49 PTHREAD_CHECK(pthread_cond_init(cond, &condattr));
50 PTHREAD_CHECK(pthread_condattr_destroy(&condattr));
52 PTHREAD_CHECK(pthread_cond_init(cond, NULL));
56 int usbi_cond_timedwait(pthread_cond_t *cond,
57 pthread_mutex_t *mutex, const struct timeval *tv)
59 struct timespec timeout;
62 #ifdef HAVE_PTHREAD_CONDATTR_SETCLOCK
63 usbi_get_monotonic_time(&timeout);
65 usbi_get_real_time(&timeout);
68 timeout.tv_sec += tv->tv_sec;
69 timeout.tv_nsec += tv->tv_usec * 1000L;
70 if (timeout.tv_nsec >= NSEC_PER_SEC) {
71 timeout.tv_nsec -= NSEC_PER_SEC;
75 r = pthread_cond_timedwait(cond, mutex, &timeout);
78 else if (r == ETIMEDOUT)
79 return LIBUSB_ERROR_TIMEOUT;
81 return LIBUSB_ERROR_OTHER;
84 unsigned int usbi_get_tid(void)
86 static _Thread_local unsigned int tl_tid;
92 #if defined(__ANDROID__)
94 #elif defined(__APPLE__)
95 #ifdef HAVE_PTHREAD_THREADID_NP
98 if (pthread_threadid_np(NULL, &thread_id) == 0)
103 tid = (int)pthread_mach_thread_np(pthread_self());
105 #elif defined(__HAIKU__)
106 tid = get_pthread_thread_id(pthread_self());
107 #elif defined(__linux__)
108 tid = (int)syscall(SYS_gettid);
109 #elif defined(__NetBSD__)
111 #elif defined(__OpenBSD__)
112 /* The following only works with OpenBSD > 5.1 as it requires
113 * real thread support. For 5.1 and earlier, -1 is returned. */
114 tid = syscall(SYS_getthrid);
115 #elif defined(__sun__)
122 /* If we don't have a thread ID, at least return a unique
123 * value that can be used to distinguish individual
125 tid = (int)(intptr_t)pthread_self();
128 return tl_tid = (unsigned int)tid;