Darwin: Fix a SIGFPE
[libusbx.git] / libusb / os / threads_posix.c
blobedf706364d1bca3dc0ab12077a34537c09e955a0
1 /*
2 * libusbx 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
22 #if defined(__linux__) || defined(__OpenBSD__)
23 # if defined(__linux__)
24 # define _GNU_SOURCE
25 # else
26 # define _BSD_SOURCE
27 # endif
28 # include <unistd.h>
29 # include <sys/syscall.h>
30 #elif defined(__APPLE__)
31 # include <mach/mach.h>
32 #elif defined(__CYGWIN__)
33 # include <windows.h>
34 #endif
36 #include "threads_posix.h"
38 int usbi_mutex_init_recursive(pthread_mutex_t *mutex, pthread_mutexattr_t *attr)
40 int err;
41 pthread_mutexattr_t stack_attr;
42 if (!attr) {
43 attr = &stack_attr;
44 err = pthread_mutexattr_init(&stack_attr);
45 if (err != 0)
46 return err;
49 /* mutexattr_settype requires _GNU_SOURCE or _XOPEN_SOURCE >= 500 on Linux */
50 err = pthread_mutexattr_settype(attr, PTHREAD_MUTEX_RECURSIVE);
51 if (err != 0)
52 goto finish;
54 err = pthread_mutex_init(mutex, attr);
56 finish:
57 if (attr == &stack_attr)
58 pthread_mutexattr_destroy(&stack_attr);
60 return err;
63 int usbi_get_tid(void)
65 int ret = -1;
66 #if defined(__ANDROID__)
67 ret = gettid();
68 #elif defined(__linux__)
69 ret = syscall(SYS_gettid);
70 #elif defined(__OpenBSD__)
71 /* The following only works with OpenBSD > 5.1 as it requires
72 real thread support. For 5.1 and earlier, -1 is returned. */
73 ret = syscall(SYS_getthrid);
74 #elif defined(__APPLE__)
75 ret = mach_thread_self();
76 mach_port_deallocate(mach_task_self(), ret);
77 #elif defined(__CYGWIN__)
78 ret = GetCurrentThreadId();
79 #endif
80 /* TODO: NetBSD thread ID support */
81 return ret;