compat_pthreads.c 7.6 KB

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