core: Make use of headers consistent across all files
[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 <config.h>
23
24 #if defined(__linux__) || defined(__OpenBSD__)
25 # if defined(__linux__)
26 #  define _GNU_SOURCE
27 # else
28 #  define _BSD_SOURCE
29 # endif
30 # include <unistd.h>
31 # include <sys/syscall.h>
32 #elif defined(__APPLE__)
33 # include <mach/mach.h>
34 #elif defined(__CYGWIN__)
35 # include <windows.h>
36 #endif
37
38 #include "threads_posix.h"
39
40 int usbi_mutex_init_recursive(pthread_mutex_t *mutex, pthread_mutexattr_t *attr)
41 {
42         int err;
43         pthread_mutexattr_t stack_attr;
44         if (!attr) {
45                 attr = &stack_attr;
46                 err = pthread_mutexattr_init(&stack_attr);
47                 if (err != 0)
48                         return err;
49         }
50
51         /* mutexattr_settype requires _GNU_SOURCE or _XOPEN_SOURCE >= 500 on Linux */
52         err = pthread_mutexattr_settype(attr, PTHREAD_MUTEX_RECURSIVE);
53         if (err != 0)
54                 goto finish;
55
56         err = pthread_mutex_init(mutex, attr);
57
58 finish:
59         if (attr == &stack_attr)
60                 pthread_mutexattr_destroy(&stack_attr);
61
62         return err;
63 }
64
65 int usbi_get_tid(void)
66 {
67         int ret = -1;
68 #if defined(__ANDROID__)
69         ret = gettid();
70 #elif defined(__linux__)
71         ret = syscall(SYS_gettid);
72 #elif defined(__OpenBSD__)
73         /* The following only works with OpenBSD > 5.1 as it requires
74            real thread support. For 5.1 and earlier, -1 is returned. */
75         ret = syscall(SYS_getthrid);
76 #elif defined(__APPLE__)
77         ret = mach_thread_self();
78         mach_port_deallocate(mach_task_self(), ret);
79 #elif defined(__CYGWIN__)
80         ret = GetCurrentThreadId();
81 #endif
82 /* TODO: NetBSD thread ID support */
83         return ret;
84 }