compat_pthreads.c 7.7 KB

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