92bb11d7a03c8e393b4d32bdd0d96c672491b53c
[platform/upstream/libusb.git] / libusb / os / threads_posix.c
1 /*
2  * libusb synchronization using POSIX Threads
3  *
4  * Copyright © 2011 Vitali Lovich <vlovich@aliph.com>
5  * Copyright © 2011 Peter Stuge <peter@stuge.se>
6  *
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.
11  *
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.
16  *
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
20  */
21
22 #include "libusbi.h"
23
24 #if defined(__ANDROID__)
25 # include <unistd.h>
26 #elif defined(__linux__) || defined(__OpenBSD__)
27 # if defined(__OpenBSD__)
28 #  define _BSD_SOURCE
29 # endif
30 # include <sys/syscall.h>
31 #endif
32
33 int usbi_cond_timedwait(pthread_cond_t *cond,
34         pthread_mutex_t *mutex, const struct timeval *tv)
35 {
36         struct timespec timeout;
37         int r;
38
39         r = usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &timeout);
40         if (r < 0)
41                 return r;
42
43         timeout.tv_sec += tv->tv_sec;
44         timeout.tv_nsec += tv->tv_usec * 1000;
45         while (timeout.tv_nsec >= 1000000000L) {
46                 timeout.tv_nsec -= 1000000000L;
47                 timeout.tv_sec++;
48         }
49
50         return pthread_cond_timedwait(cond, mutex, &timeout);
51 }
52
53 int usbi_get_tid(void)
54 {
55         int ret;
56 #if defined(__ANDROID__)
57         ret = gettid();
58 #elif defined(__linux__)
59         ret = syscall(SYS_gettid);
60 #elif defined(__OpenBSD__)
61         /* The following only works with OpenBSD > 5.1 as it requires
62            real thread support. For 5.1 and earlier, -1 is returned. */
63         ret = syscall(SYS_getthrid);
64 #elif defined(__APPLE__)
65         ret = (int)pthread_mach_thread_np(pthread_self());
66 #elif defined(__CYGWIN__)
67         ret = GetCurrentThreadId();
68 #else
69         ret = -1;
70 #endif
71 /* TODO: NetBSD thread ID support */
72         return ret;
73 }