compat_pthreads.c 8.6 KB

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