threads_posix.c 2.2 KB

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