compat_pthreads.c 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2016, 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. #define _GNU_SOURCE
  12. #include "orconfig.h"
  13. #include <pthread.h>
  14. #include <signal.h>
  15. #include <time.h>
  16. #include "compat.h"
  17. #include "torlog.h"
  18. #include "util.h"
  19. #ifdef __APPLE__
  20. #undef CLOCK_MONOTONIC
  21. #undef HAVE_CLOCK_GETTIME
  22. #endif
  23. /** Wraps a void (*)(void*) function and its argument so we can
  24. * invoke them in a way pthreads would expect.
  25. */
  26. typedef struct tor_pthread_data_t {
  27. void (*func)(void *);
  28. void *data;
  29. } tor_pthread_data_t;
  30. /** Given a tor_pthread_data_t <b>_data</b>, call _data-&gt;func(d-&gt;data)
  31. * and free _data. Used to make sure we can call functions the way pthread
  32. * expects. */
  33. static void *
  34. tor_pthread_helper_fn(void *_data)
  35. {
  36. tor_pthread_data_t *data = _data;
  37. void (*func)(void*);
  38. void *arg;
  39. /* mask signals to worker threads to avoid SIGPIPE, etc */
  40. sigset_t sigs;
  41. /* We're in a subthread; don't handle any signals here. */
  42. sigfillset(&sigs);
  43. pthread_sigmask(SIG_SETMASK, &sigs, NULL);
  44. func = data->func;
  45. arg = data->data;
  46. tor_free(_data);
  47. func(arg);
  48. return NULL;
  49. }
  50. /**
  51. * A pthread attribute to make threads start detached.
  52. */
  53. static pthread_attr_t attr_detached;
  54. /** True iff we've called tor_threads_init() */
  55. static int threads_initialized = 0;
  56. /** Minimalist interface to run a void function in the background. On
  57. * Unix calls pthread_create, on win32 calls beginthread. Returns -1 on
  58. * failure.
  59. * func should not return, but rather should call spawn_exit.
  60. *
  61. * NOTE: if <b>data</b> is used, it should not be allocated on the stack,
  62. * since in a multithreaded environment, there is no way to be sure that
  63. * the caller's stack will still be around when the called function is
  64. * running.
  65. */
  66. int
  67. spawn_func(void (*func)(void *), void *data)
  68. {
  69. pthread_t thread;
  70. tor_pthread_data_t *d;
  71. if (PREDICT_UNLIKELY(!threads_initialized)) {
  72. tor_threads_init();
  73. }
  74. d = tor_malloc(sizeof(tor_pthread_data_t));
  75. d->data = data;
  76. d->func = func;
  77. if (pthread_create(&thread, &attr_detached, tor_pthread_helper_fn, d)) {
  78. tor_free(d);
  79. return -1;
  80. }
  81. return 0;
  82. }
  83. /** End the current thread/process.
  84. */
  85. void
  86. spawn_exit(void)
  87. {
  88. pthread_exit(NULL);
  89. }
  90. /** A mutex attribute that we're going to use to tell pthreads that we want
  91. * "recursive" mutexes (i.e., once we can re-lock if we're already holding
  92. * them.) */
  93. static pthread_mutexattr_t attr_recursive;
  94. /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
  95. * up with tor_mutex_init() or tor_mutex_new(); not both. */
  96. void
  97. tor_mutex_init(tor_mutex_t *mutex)
  98. {
  99. if (PREDICT_UNLIKELY(!threads_initialized))
  100. tor_threads_init();
  101. const int err = pthread_mutex_init(&mutex->mutex, &attr_recursive);
  102. if (PREDICT_UNLIKELY(err)) {
  103. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  104. tor_fragile_assert();
  105. }
  106. }
  107. /** As tor_mutex_init, but initialize a mutex suitable that may be
  108. * non-recursive, if the OS supports that. */
  109. void
  110. tor_mutex_init_nonrecursive(tor_mutex_t *mutex)
  111. {
  112. int err;
  113. if (PREDICT_UNLIKELY(!threads_initialized))
  114. tor_threads_init();
  115. err = pthread_mutex_init(&mutex->mutex, NULL);
  116. if (PREDICT_UNLIKELY(err)) {
  117. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  118. tor_fragile_assert();
  119. }
  120. }
  121. /** Wait until <b>m</b> is free, then acquire it. */
  122. void
  123. tor_mutex_acquire(tor_mutex_t *m)
  124. {
  125. int err;
  126. tor_assert(m);
  127. err = pthread_mutex_lock(&m->mutex);
  128. if (PREDICT_UNLIKELY(err)) {
  129. log_err(LD_GENERAL, "Error %d locking a mutex.", err);
  130. tor_fragile_assert();
  131. }
  132. }
  133. /** Release the lock <b>m</b> so another thread can have it. */
  134. void
  135. tor_mutex_release(tor_mutex_t *m)
  136. {
  137. int err;
  138. tor_assert(m);
  139. err = pthread_mutex_unlock(&m->mutex);
  140. if (PREDICT_UNLIKELY(err)) {
  141. log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
  142. tor_fragile_assert();
  143. }
  144. }
  145. /** Clean up the mutex <b>m</b> so that it no longer uses any system
  146. * resources. Does not free <b>m</b>. This function must only be called on
  147. * mutexes from tor_mutex_init(). */
  148. void
  149. tor_mutex_uninit(tor_mutex_t *m)
  150. {
  151. int err;
  152. tor_assert(m);
  153. err = pthread_mutex_destroy(&m->mutex);
  154. if (PREDICT_UNLIKELY(err)) {
  155. log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
  156. tor_fragile_assert();
  157. }
  158. }
  159. /** Return an integer representing this thread. */
  160. unsigned long
  161. tor_get_thread_id(void)
  162. {
  163. union {
  164. pthread_t thr;
  165. unsigned long id;
  166. } r;
  167. r.thr = pthread_self();
  168. return r.id;
  169. }
  170. /* Conditions. */
  171. /** Initialize an already-allocated condition variable. */
  172. int
  173. tor_cond_init(tor_cond_t *cond)
  174. {
  175. pthread_condattr_t condattr;
  176. memset(cond, 0, sizeof(tor_cond_t));
  177. /* Default condition attribute. Might be used if clock monotonic is
  178. * available else this won't affect anything. */
  179. if (pthread_condattr_init(&condattr)) {
  180. return -1;
  181. }
  182. #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) \
  183. && defined(HAVE_PTHREAD_CONDATTR_SETCLOCK)
  184. /* Use monotonic time so when we timedwait() on it, any clock adjustment
  185. * won't affect the timeout value. */
  186. if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
  187. return -1;
  188. }
  189. #endif
  190. if (pthread_cond_init(&cond->cond, &condattr)) {
  191. return -1;
  192. }
  193. return 0;
  194. }
  195. /** Release all resources held by <b>cond</b>, but do not free <b>cond</b>
  196. * itself. */
  197. void
  198. tor_cond_uninit(tor_cond_t *cond)
  199. {
  200. if (pthread_cond_destroy(&cond->cond)) {
  201. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  202. return;
  203. }
  204. }
  205. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  206. * (If <b>tv</b> is set, and that amount of time passes with no signal to
  207. * <b>cond</b>, return anyway. All waiters on the condition must wait holding
  208. * the same <b>mutex</b>. All signallers should hold that mutex. The mutex
  209. * needs to have been allocated with tor_mutex_init_for_cond().
  210. *
  211. * Returns 0 on success, -1 on failure, 1 on timeout. */
  212. int
  213. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex, const struct timeval *tv)
  214. {
  215. int r;
  216. if (tv == NULL) {
  217. while (1) {
  218. r = pthread_cond_wait(&cond->cond, &mutex->mutex);
  219. if (r == EINTR) {
  220. /* EINTR should be impossible according to POSIX, but POSIX, like the
  221. * Pirate's Code, is apparently treated "more like what you'd call
  222. * guidelines than actual rules." */
  223. continue;
  224. }
  225. return r ? -1 : 0;
  226. }
  227. } else {
  228. struct timeval tvnow, tvsum;
  229. struct timespec ts;
  230. while (1) {
  231. #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
  232. if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0) {
  233. return -1;
  234. }
  235. tvnow.tv_sec = ts.tv_sec;
  236. tvnow.tv_usec = ts.tv_nsec / 1000;
  237. timeradd(tv, &tvnow, &tvsum);
  238. #else
  239. if (gettimeofday(&tvnow, NULL) < 0)
  240. return -1;
  241. timeradd(tv, &tvnow, &tvsum);
  242. #endif /* HAVE_CLOCK_GETTIME, CLOCK_MONOTONIC */
  243. ts.tv_sec = tvsum.tv_sec;
  244. ts.tv_nsec = tvsum.tv_usec * 1000;
  245. r = pthread_cond_timedwait(&cond->cond, &mutex->mutex, &ts);
  246. if (r == 0)
  247. return 0;
  248. else if (r == ETIMEDOUT)
  249. return 1;
  250. else if (r == EINTR)
  251. continue;
  252. else
  253. return -1;
  254. }
  255. }
  256. }
  257. /** Wake up one of the waiters on <b>cond</b>. */
  258. void
  259. tor_cond_signal_one(tor_cond_t *cond)
  260. {
  261. pthread_cond_signal(&cond->cond);
  262. }
  263. /** Wake up all of the waiters on <b>cond</b>. */
  264. void
  265. tor_cond_signal_all(tor_cond_t *cond)
  266. {
  267. pthread_cond_broadcast(&cond->cond);
  268. }
  269. int
  270. tor_threadlocal_init(tor_threadlocal_t *threadlocal)
  271. {
  272. int err = pthread_key_create(&threadlocal->key, NULL);
  273. return err ? -1 : 0;
  274. }
  275. void
  276. tor_threadlocal_destroy(tor_threadlocal_t *threadlocal)
  277. {
  278. pthread_key_delete(threadlocal->key);
  279. memset(threadlocal, 0, sizeof(tor_threadlocal_t));
  280. }
  281. void *
  282. tor_threadlocal_get(tor_threadlocal_t *threadlocal)
  283. {
  284. return pthread_getspecific(threadlocal->key);
  285. }
  286. void
  287. tor_threadlocal_set(tor_threadlocal_t *threadlocal, void *value)
  288. {
  289. int err = pthread_setspecific(threadlocal->key, value);
  290. tor_assert(err == 0);
  291. }
  292. /** Set up common structures for use by threading. */
  293. void
  294. tor_threads_init(void)
  295. {
  296. if (!threads_initialized) {
  297. pthread_mutexattr_init(&attr_recursive);
  298. pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE);
  299. const int ret1 = pthread_attr_init(&attr_detached);
  300. tor_assert(ret1 == 0);
  301. #ifndef PTHREAD_CREATE_DETACHED
  302. #define PTHREAD_CREATE_DETACHED 1
  303. #endif
  304. const int ret2 =
  305. pthread_attr_setdetachstate(&attr_detached, PTHREAD_CREATE_DETACHED);
  306. tor_assert(ret2 == 0);
  307. threads_initialized = 1;
  308. set_main_thread();
  309. }
  310. }