compat_pthreads.c 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. #include "orconfig.h"
  12. #include <pthread.h>
  13. #include <signal.h>
  14. #include <time.h>
  15. #include "compat.h"
  16. #include "torlog.h"
  17. #include "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. /** A mutex attribute that we're going to use to tell pthreads that we want
  86. * "recursive" mutexes (i.e., once we can re-lock if we're already holding
  87. * them.) */
  88. static pthread_mutexattr_t attr_recursive;
  89. /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
  90. * up with tor_mutex_init() or tor_mutex_new(); not both. */
  91. void
  92. tor_mutex_init(tor_mutex_t *mutex)
  93. {
  94. if (PREDICT_UNLIKELY(!threads_initialized))
  95. tor_threads_init();
  96. const int err = pthread_mutex_init(&mutex->mutex, &attr_recursive);
  97. if (PREDICT_UNLIKELY(err)) {
  98. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  99. tor_fragile_assert();
  100. }
  101. }
  102. /** As tor_mutex_init, but initialize a mutex suitable that may be
  103. * non-recursive, if the OS supports that. */
  104. void
  105. tor_mutex_init_nonrecursive(tor_mutex_t *mutex)
  106. {
  107. int err;
  108. if (PREDICT_UNLIKELY(!threads_initialized))
  109. tor_threads_init();
  110. err = pthread_mutex_init(&mutex->mutex, NULL);
  111. if (PREDICT_UNLIKELY(err)) {
  112. log_err(LD_GENERAL, "Error %d creating a mutex.", err);
  113. tor_fragile_assert();
  114. }
  115. }
  116. /** Wait until <b>m</b> is free, then acquire it. */
  117. void
  118. tor_mutex_acquire(tor_mutex_t *m)
  119. {
  120. int err;
  121. tor_assert(m);
  122. err = pthread_mutex_lock(&m->mutex);
  123. if (PREDICT_UNLIKELY(err)) {
  124. log_err(LD_GENERAL, "Error %d locking a mutex.", err);
  125. tor_fragile_assert();
  126. }
  127. }
  128. /** Release the lock <b>m</b> so another thread can have it. */
  129. void
  130. tor_mutex_release(tor_mutex_t *m)
  131. {
  132. int err;
  133. tor_assert(m);
  134. err = pthread_mutex_unlock(&m->mutex);
  135. if (PREDICT_UNLIKELY(err)) {
  136. log_err(LD_GENERAL, "Error %d unlocking a mutex.", err);
  137. tor_fragile_assert();
  138. }
  139. }
  140. /** Clean up the mutex <b>m</b> so that it no longer uses any system
  141. * resources. Does not free <b>m</b>. This function must only be called on
  142. * mutexes from tor_mutex_init(). */
  143. void
  144. tor_mutex_uninit(tor_mutex_t *m)
  145. {
  146. int err;
  147. tor_assert(m);
  148. err = pthread_mutex_destroy(&m->mutex);
  149. if (PREDICT_UNLIKELY(err)) {
  150. log_err(LD_GENERAL, "Error %d destroying a mutex.", err);
  151. tor_fragile_assert();
  152. }
  153. }
  154. /** Return an integer representing this thread. */
  155. unsigned long
  156. tor_get_thread_id(void)
  157. {
  158. union {
  159. pthread_t thr;
  160. unsigned long id;
  161. } r;
  162. r.thr = pthread_self();
  163. return r.id;
  164. }
  165. /* Conditions. */
  166. /** Initialize an already-allocated condition variable. */
  167. int
  168. tor_cond_init(tor_cond_t *cond)
  169. {
  170. pthread_condattr_t condattr;
  171. memset(cond, 0, sizeof(tor_cond_t));
  172. /* Default condition attribute. Might be used if clock monotonic is
  173. * available else this won't affect anything. */
  174. if (pthread_condattr_init(&condattr)) {
  175. return -1;
  176. }
  177. #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) \
  178. && defined(HAVE_PTHREAD_CONDATTR_SETCLOCK)
  179. /* Use monotonic time so when we timedwait() on it, any clock adjustment
  180. * won't affect the timeout value. */
  181. if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
  182. return -1;
  183. }
  184. #endif
  185. if (pthread_cond_init(&cond->cond, &condattr)) {
  186. return -1;
  187. }
  188. return 0;
  189. }
  190. /** Release all resources held by <b>cond</b>, but do not free <b>cond</b>
  191. * itself. */
  192. void
  193. tor_cond_uninit(tor_cond_t *cond)
  194. {
  195. if (pthread_cond_destroy(&cond->cond)) {
  196. log_warn(LD_GENERAL,"Error freeing condition: %s", strerror(errno));
  197. return;
  198. }
  199. }
  200. /** Wait until one of the tor_cond_signal functions is called on <b>cond</b>.
  201. * (If <b>tv</b> is set, and that amount of time passes with no signal to
  202. * <b>cond</b>, return anyway. All waiters on the condition must wait holding
  203. * the same <b>mutex</b>. All signallers should hold that mutex. The mutex
  204. * needs to have been allocated with tor_mutex_init_for_cond().
  205. *
  206. * Returns 0 on success, -1 on failure, 1 on timeout. */
  207. int
  208. tor_cond_wait(tor_cond_t *cond, tor_mutex_t *mutex, const struct timeval *tv)
  209. {
  210. int r;
  211. if (tv == NULL) {
  212. while (1) {
  213. r = pthread_cond_wait(&cond->cond, &mutex->mutex);
  214. if (r == EINTR) {
  215. /* EINTR should be impossible according to POSIX, but POSIX, like the
  216. * Pirate's Code, is apparently treated "more like what you'd call
  217. * guidelines than actual rules." */
  218. continue;
  219. }
  220. return r ? -1 : 0;
  221. }
  222. } else {
  223. struct timeval tvnow, tvsum;
  224. struct timespec ts;
  225. while (1) {
  226. #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
  227. if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0) {
  228. return -1;
  229. }
  230. tvnow.tv_sec = ts.tv_sec;
  231. tvnow.tv_usec = ts.tv_nsec / 1000;
  232. timeradd(tv, &tvnow, &tvsum);
  233. #else
  234. if (gettimeofday(&tvnow, NULL) < 0)
  235. return -1;
  236. timeradd(tv, &tvnow, &tvsum);
  237. #endif /* HAVE_CLOCK_GETTIME, CLOCK_MONOTONIC */
  238. ts.tv_sec = tvsum.tv_sec;
  239. ts.tv_nsec = tvsum.tv_usec * 1000;
  240. r = pthread_cond_timedwait(&cond->cond, &mutex->mutex, &ts);
  241. if (r == 0)
  242. return 0;
  243. else if (r == ETIMEDOUT)
  244. return 1;
  245. else if (r == EINTR)
  246. continue;
  247. else
  248. return -1;
  249. }
  250. }
  251. }
  252. /** Wake up one of the waiters on <b>cond</b>. */
  253. void
  254. tor_cond_signal_one(tor_cond_t *cond)
  255. {
  256. pthread_cond_signal(&cond->cond);
  257. }
  258. /** Wake up all of the waiters on <b>cond</b>. */
  259. void
  260. tor_cond_signal_all(tor_cond_t *cond)
  261. {
  262. pthread_cond_broadcast(&cond->cond);
  263. }
  264. int
  265. tor_threadlocal_init(tor_threadlocal_t *threadlocal)
  266. {
  267. int err = pthread_key_create(&threadlocal->key, NULL);
  268. return err ? -1 : 0;
  269. }
  270. void
  271. tor_threadlocal_destroy(tor_threadlocal_t *threadlocal)
  272. {
  273. pthread_key_delete(threadlocal->key);
  274. memset(threadlocal, 0, sizeof(tor_threadlocal_t));
  275. }
  276. void *
  277. tor_threadlocal_get(tor_threadlocal_t *threadlocal)
  278. {
  279. return pthread_getspecific(threadlocal->key);
  280. }
  281. void
  282. tor_threadlocal_set(tor_threadlocal_t *threadlocal, void *value)
  283. {
  284. int err = pthread_setspecific(threadlocal->key, value);
  285. tor_assert(err == 0);
  286. }
  287. /** Set up common structures for use by threading. */
  288. void
  289. tor_threads_init(void)
  290. {
  291. if (!threads_initialized) {
  292. pthread_mutexattr_init(&attr_recursive);
  293. pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE);
  294. const int ret1 = pthread_attr_init(&attr_detached);
  295. tor_assert(ret1 == 0);
  296. #ifndef PTHREAD_CREATE_DETACHED
  297. #define PTHREAD_CREATE_DETACHED 1
  298. #endif
  299. const int ret2 =
  300. pthread_attr_setdetachstate(&attr_detached, PTHREAD_CREATE_DETACHED);
  301. tor_assert(ret2 == 0);
  302. threads_initialized = 1;
  303. set_main_thread();
  304. }
  305. }