Core: Add a timestamping and thread ID to logging
[platform/upstream/libusb.git] / libusb / os / threads_posix.c
1 /*
2  * libusbx 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 #if defined(__linux__)
23 # include <unistd.h>
24 # include <sys/syscall.h>
25 #elif defined(__APPLE__)
26 # include <mach/mach.h>
27 #endif
28
29 #ifdef _XOPEN_SOURCE
30 # if _XOPEN_SOURCE < 500
31 #  undef _XOPEN_SOURCE
32 #  define _XOPEN_SOURCE 500
33 # endif
34 #else
35 #define _XOPEN_SOURCE 500
36 #endif /* _XOPEN_SOURCE */
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         err = pthread_mutexattr_settype(attr, PTHREAD_MUTEX_RECURSIVE);
52         if (err != 0)
53                 goto finish;
54
55         err = pthread_mutex_init(mutex, attr);
56
57 finish:
58         if (attr == &stack_attr)
59                 pthread_mutexattr_destroy(&stack_attr);
60
61         return err;
62 }
63
64 int usbi_get_tid(void)
65 {
66         int ret = -1;
67 #if defined(__linux__)
68         ret = syscall(SYS_gettid);
69 #elif defined(__APPLE__)
70         ret = mach_thread_self();
71         mach_port_deallocate(mach_task_self(), ret);
72 #endif
73 /* TODO: OpenBSD and NetBSD thread ID support */
74         return ret;
75 }