compat_pthreads.c 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compat_pthreads.c
  7. *
  8. * \brief Implementation for the pthreads-based multithreading backend
  9. * functions.
  10. */
  11. #include "orconfig.h"
  12. #include <pthread.h>
  13. #include <signal.h>
  14. #include <time.h>
  15. #include "common/compat.h"
  16. #include "common/torlog.h"
  17. #include "common/util.h"
  18. /** Wraps a void (*)(void*) function and its argument so we can
  19. * invoke them in a way pthreads would expect.
  20. */
  21. typedef struct tor_pthread_data_t {
  22. void (*func)(void *);
  23. void *data;
  24. } tor_pthread_data_t;
  25. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  26. * and free _data. Used to make sure we can call functions the way pthread
  27. * expects. */
  28. static void *
  29. tor_pthread_helper_fn(void *_data)
  30. {
  31. tor_pthread_data_t *data = _data;
  32. void (*func)(void*);
  33. void *arg;
  34. /* mask signals to worker threads to avoid SIGPIPE, etc */
  35. sigset_t sigs;
  36. /* We're in a subthread; don't handle any signals here. */
  37. sigfillset(&sigs);
  38. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  39. func = data->func;
  40. arg = data->data;
  41. tor_free(_data);
  42. func(arg);
  43. return NULL;
  44. }
  45. /**
  46. * A pthread attribute to make threads start detached.
  47. */
  48. static pthread_attr_t attr_detached;
  49. /** True iff we've called tor_threads_init() */
  50. static int threads_initialized = 0;
  51. /** Minimalist interface to run a void function in the background. On
  52. * Unix calls pthread_create, on win32 calls beginthread. Returns -1 on
  53. * failure.
  54. * func should not return, but rather should call spawn_exit.
  55. *
  56. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  57. * since in a multithreaded environment, there is no way to be sure that
  58. * the caller's stack will still be around when the called function is
  59. * running.
  60. */
  61. int
  62. spawn_func(void (*func)(void *), void *data)
  63. {
  64. pthread_t thread;
  65. tor_pthread_data_t *d;
  66. if (PREDICT_UNLIKELY(!threads_initialized)) {
  67. tor_threads_init();
  68. }
  69. d = tor_malloc(sizeof(tor_pthread_data_t));
  70. d->data = data;
  71. d->func = func;
  72. if (pthread_create(&thread, &attr_detached, tor_pthread_helper_fn, d)) {
  73. tor_free(d);
  74. return -1;
  75. }
  76. return 0;
  77. }
  78. /** End the current thread/process.
  79. */
  80. void
  81. spawn_exit(void)
  82. {
  83. pthread_exit(NULL);
  84. }
  85. /** Return an integer representing this thread. */
  86. unsigned long
  87. tor_get_thread_id(void)
  88. {
  89. union {
  90. pthread_t thr;
  91. unsigned long id;
  92. } r;
  93. r.thr = pthread_self();
  94. return r.id;
  95. }
  96. /* Conditions. */
  97. /** Initialize an already-allocated condition variable. */
  98. int
  99. tor_cond_init(tor_cond_t *cond)
  100. {
  101. pthread_condattr_t condattr;
  102. memset(cond, 0, sizeof(tor_cond_t));
  103. /* Default condition attribute. Might be used if clock monotonic is
  104. * available else this won't affect anything. */
  105. if (pthread_condattr_init(&condattr)) {
  106. return -1;
  107. }
  108. #if defined(HAVE_CLOCK_GETTIME)
  109. #if defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && \
  110. defined(CLOCK_MONOTONIC)
  111. /* Use monotonic time so when we timedwait() on it, any clock adjustment
  112. * won't affect the timeout value. */
  113. if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
  114. return -1;
  115. }
  116. #define USE_COND_CLOCK CLOCK_MONOTONIC
  117. #else /* !(defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && ...) */
  118. /* On OSX Sierra, there is no pthread_condattr_setclock, so we are stuck
  119. * with the realtime clock.
  120. */
  121. #define USE_COND_CLOCK CLOCK_REALTIME
  122. #endif /* defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && ... */
  123. #endif /* defined(HAVE_CLOCK_GETTIME) */
  124. if (pthread_cond_init(&cond->cond, &condattr)) {
  125. return -1;
  126. }
  127. return 0;
  128. }
  129. /** Release all resources held by <b>cond</b>, but do not free <b>cond</b>
  130. * itself. */
  131. void
  132. tor_cond_uninit(tor_cond_t *cond)
  133. {
  134. if (pthread_cond_destroy(&cond->cond)) {
  135. // LCOV_EXCL_START
  136. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  137. return;
  138. // LCOV_EXCL_STOP
  139. }
  140. }
  141. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  142. * (If <b>tv</b> is set, and that amount of time passes with no signal to
  143. * <b>cond</b>, return anyway. All waiters on the condition must wait holding
  144. * the same <b>mutex</b>. All signallers should hold that mutex. The mutex
  145. * needs to have been allocated with tor_mutex_init_for_cond().
  146. *
  147. * Returns 0 on success, -1 on failure, 1 on timeout. */
  148. int
  149. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex, const struct timeval *tv)
  150. {
  151. int r;
  152. if (tv == NULL) {
  153. while (1) {
  154. r = pthread_cond_wait(&cond->cond, &mutex->mutex);
  155. if (r == EINTR) {
  156. /* EINTR should be impossible according to POSIX, but POSIX, like the
  157. * Pirate's Code, is apparently treated "more like what you'd call
  158. * guidelines than actual rules." */
  159. continue; // LCOV_EXCL_LINE
  160. }
  161. return r ? -1 : 0;
  162. }
  163. } else {
  164. struct timeval tvnow, tvsum;
  165. struct timespec ts;
  166. while (1) {
  167. #if defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK)
  168. if (clock_gettime(USE_COND_CLOCK, &ts) < 0) {
  169. return -1;
  170. }
  171. tvnow.tv_sec = ts.tv_sec;
  172. tvnow.tv_usec = (int)(ts.tv_nsec / 1000);
  173. timeradd(tv, &tvnow, &tvsum);
  174. #else /* !(defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK)) */
  175. if (gettimeofday(&tvnow, NULL) < 0)
  176. return -1;
  177. timeradd(tv, &tvnow, &tvsum);
  178. #endif /* defined(HAVE_CLOCK_GETTIME) && defined(USE_COND_CLOCK) */
  179. ts.tv_sec = tvsum.tv_sec;
  180. ts.tv_nsec = tvsum.tv_usec * 1000;
  181. r = pthread_cond_timedwait(&cond->cond, &mutex->mutex, &ts);
  182. if (r == 0)
  183. return 0;
  184. else if (r == ETIMEDOUT)
  185. return 1;
  186. else if (r == EINTR)
  187. continue;
  188. else
  189. return -1;
  190. }
  191. }
  192. }
  193. /** Wake up one of the waiters on <b>cond</b>. */
  194. void
  195. tor_cond_signal_one(tor_cond_t *cond)
  196. {
  197. pthread_cond_signal(&cond->cond);
  198. }
  199. /** Wake up all of the waiters on <b>cond</b>. */
  200. void
  201. tor_cond_signal_all(tor_cond_t *cond)
  202. {
  203. pthread_cond_broadcast(&cond->cond);
  204. }
  205. int
  206. tor_threadlocal_init(tor_threadlocal_t *threadlocal)
  207. {
  208. int err = pthread_key_create(&threadlocal->key, NULL);
  209. return err ? -1 : 0;
  210. }
  211. void
  212. tor_threadlocal_destroy(tor_threadlocal_t *threadlocal)
  213. {
  214. pthread_key_delete(threadlocal->key);
  215. memset(threadlocal, 0, sizeof(tor_threadlocal_t));
  216. }
  217. void *
  218. tor_threadlocal_get(tor_threadlocal_t *threadlocal)
  219. {
  220. return pthread_getspecific(threadlocal->key);
  221. }
  222. void
  223. tor_threadlocal_set(tor_threadlocal_t *threadlocal, void *value)
  224. {
  225. int err = pthread_setspecific(threadlocal->key, value);
  226. tor_assert(err == 0);
  227. }
  228. /** Set up common structures for use by threading. */
  229. void
  230. tor_threads_init(void)
  231. {
  232. if (!threads_initialized) {
  233. tor_locking_init();
  234. const int ret1 = pthread_attr_init(&attr_detached);
  235. tor_assert(ret1 == 0);
  236. #ifndef PTHREAD_CREATE_DETACHED
  237. #define PTHREAD_CREATE_DETACHED 1
  238. #endif
  239. const int ret2 =
  240. pthread_attr_setdetachstate(&attr_detached, PTHREAD_CREATE_DETACHED);
  241. tor_assert(ret2 == 0);
  242. threads_initialized = 1;
  243. set_main_thread();
  244. }
  245. }