workqueue.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /* Copyright (c) 2013, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #include "orconfig.h"
  4. #include "compat.h"
  5. #include "compat_threads.h"
  6. #include "util.h"
  7. #include "workqueue.h"
  8. #include "tor_queue.h"
  9. #include "torlog.h"
  10. struct threadpool_s {
  11. /** An array of pointers to workerthread_t: one for each running worker
  12. * thread. */
  13. struct workerthread_s **threads;
  14. /** Index of the next thread that we'll give work to.*/
  15. int next_for_work;
  16. /** Number of elements in threads. */
  17. int n_threads;
  18. /** Mutex to protect all the above fields. */
  19. tor_mutex_t lock;
  20. /** A reply queue to use when constructing new threads. */
  21. replyqueue_t *reply_queue;
  22. /** Functions used to allocate and free thread state. */
  23. void *(*new_thread_state_fn)(void*);
  24. void (*free_thread_state_fn)(void*);
  25. void *new_thread_state_arg;
  26. };
  27. struct workqueue_entry_s {
  28. /** The next workqueue_entry_t that's pending on the same thread or
  29. * reply queue. */
  30. TOR_TAILQ_ENTRY(workqueue_entry_s) next_work;
  31. /** The thread to which this workqueue_entry_t was assigned. This field
  32. * is set when the workqueue_entry_t is created, and won't be cleared until
  33. * after it's handled in the main thread. */
  34. struct workerthread_s *on_thread;
  35. /** True iff this entry is waiting for a worker to start processing it. */
  36. uint8_t pending;
  37. /** Function to run in the worker thread. */
  38. int (*fn)(void *state, void *arg);
  39. /** Function to run while processing the reply queue. */
  40. void (*reply_fn)(void *arg);
  41. /** Argument for the above functions. */
  42. void *arg;
  43. };
  44. struct replyqueue_s {
  45. /** Mutex to protect the answers field */
  46. tor_mutex_t lock;
  47. /** Doubly-linked list of answers that the reply queue needs to handle. */
  48. TOR_TAILQ_HEAD(, workqueue_entry_s) answers;
  49. /** Mechanism to wake up the main thread when it is receiving answers. */
  50. alert_sockets_t alert;
  51. };
  52. /** A worker thread represents a single thread in a thread pool. To avoid
  53. * contention, each gets its own queue. This breaks the guarantee that that
  54. * queued work will get executed strictly in order. */
  55. typedef struct workerthread_s {
  56. /** Lock to protect all fields of this thread and its queue. */
  57. tor_mutex_t lock;
  58. /** Condition variable that we wait on when we have no work, and which
  59. * gets signaled when our queue becomes nonempty. */
  60. tor_cond_t condition;
  61. /** Queue of pending work that we have to do. */
  62. TOR_TAILQ_HEAD(, workqueue_entry_s) work;
  63. /** True iff this thread is currently in its loop. */
  64. unsigned is_running;
  65. /** True iff this thread has crashed or is shut down for some reason. */
  66. unsigned is_shut_down;
  67. /** True if we're waiting for more elements to get added to the queue. */
  68. unsigned waiting;
  69. /** User-supplied state field that we pass to the worker functions of each
  70. * work item. */
  71. void *state;
  72. /** Reply queue to which we pass our results. */
  73. replyqueue_t *reply_queue;
  74. } workerthread_t;
  75. static void queue_reply(replyqueue_t *queue, workqueue_entry_t *work);
  76. /** Allocate and return a new workqueue_entry_t, set up to run the function
  77. * <b>fn</b> in the worker thread, and <b>reply_fn</b> in the main
  78. * thread. See threadpool_queue_work() for full documentation. */
  79. static workqueue_entry_t *
  80. workqueue_entry_new(int (*fn)(void*, void*),
  81. void (*reply_fn)(void*),
  82. void *arg)
  83. {
  84. workqueue_entry_t *ent = tor_malloc_zero(sizeof(workqueue_entry_t));
  85. ent->fn = fn;
  86. ent->reply_fn = reply_fn;
  87. ent->arg = arg;
  88. return ent;
  89. }
  90. /**
  91. * Release all storage held in <b>ent</b>. Call only when <b>ent</b> is not on
  92. * any queue.
  93. */
  94. static void
  95. workqueue_entry_free(workqueue_entry_t *ent)
  96. {
  97. if (!ent)
  98. return;
  99. tor_free(ent);
  100. }
  101. /**
  102. * Cancel a workqueue_entry_t that has been returned from
  103. * threadpool_queue_work.
  104. *
  105. * You must not call this function on any work whose reply function has been
  106. * executed in the main thread; that will cause undefined behavior (probably,
  107. * a crash).
  108. *
  109. * If the work is cancelled, this function return the argument passed to the
  110. * work function. It is the caller's responsibility to free this storage.
  111. *
  112. * This function will have no effect if the worker thread has already executed
  113. * or begun to execute the work item. In that case, it will return NULL.
  114. */
  115. void *
  116. workqueue_entry_cancel(workqueue_entry_t *ent)
  117. {
  118. int cancelled = 0;
  119. void *result = NULL;
  120. tor_mutex_acquire(&ent->on_thread->lock);
  121. if (ent->pending) {
  122. TOR_TAILQ_REMOVE(&ent->on_thread->work, ent, next_work);
  123. cancelled = 1;
  124. result = ent->arg;
  125. }
  126. tor_mutex_release(&ent->on_thread->lock);
  127. if (cancelled) {
  128. tor_free(ent);
  129. }
  130. return result;
  131. }
  132. /**
  133. * Main function for the worker thread.
  134. */
  135. static void
  136. worker_thread_main(void *thread_)
  137. {
  138. workerthread_t *thread = thread_;
  139. workqueue_entry_t *work;
  140. int result;
  141. tor_mutex_acquire(&thread->lock);
  142. thread->is_running = 1;
  143. while (1) {
  144. /* lock must be held at this point. */
  145. while (!TOR_TAILQ_EMPTY(&thread->work)) {
  146. /* lock must be held at this point. */
  147. work = TOR_TAILQ_FIRST(&thread->work);
  148. TOR_TAILQ_REMOVE(&thread->work, work, next_work);
  149. work->pending = 0;
  150. tor_mutex_release(&thread->lock);
  151. /* We run the work function without holding the thread lock. This
  152. * is the main thread's first opportunity to give us more work. */
  153. result = work->fn(thread->state, work->arg);
  154. /* Queue the reply for the main thread. */
  155. queue_reply(thread->reply_queue, work);
  156. tor_mutex_acquire(&thread->lock);
  157. /* We may need to exit the thread. */
  158. if (result >= WQ_RPL_ERROR) {
  159. thread->is_running = 0;
  160. thread->is_shut_down = 1;
  161. tor_mutex_release(&thread->lock);
  162. return;
  163. }
  164. }
  165. /* At this point the lock is held, and there is no work in this thread's
  166. * queue. */
  167. /* TODO: Try work-stealing. */
  168. /* TODO: support an idle-function */
  169. /* Okay. Now, wait till somebody has work for us. */
  170. thread->waiting = 1;
  171. if (tor_cond_wait(&thread->condition, &thread->lock, NULL) < 0) {
  172. /* XXXX ERROR */
  173. }
  174. thread->waiting = 0;
  175. }
  176. }
  177. /** Put a reply on the reply queue. The reply must not currently be on
  178. * any thread's work queue. */
  179. static void
  180. queue_reply(replyqueue_t *queue, workqueue_entry_t *work)
  181. {
  182. int was_empty;
  183. tor_mutex_acquire(&queue->lock);
  184. was_empty = TOR_TAILQ_EMPTY(&queue->answers);
  185. TOR_TAILQ_INSERT_TAIL(&queue->answers, work, next_work);
  186. tor_mutex_release(&queue->lock);
  187. if (was_empty) {
  188. if (queue->alert.alert_fn(queue->alert.write_fd) < 0) {
  189. /* XXXX complain! */
  190. }
  191. }
  192. }
  193. /** Allocate and start a new worker thread to use state object <b>state</b>,
  194. * and send responses to <b>replyqueue</b>. */
  195. static workerthread_t *
  196. workerthread_new(void *state, replyqueue_t *replyqueue)
  197. {
  198. workerthread_t *thr = tor_malloc_zero(sizeof(workerthread_t));
  199. tor_mutex_init_for_cond(&thr->lock);
  200. tor_cond_init(&thr->condition);
  201. TOR_TAILQ_INIT(&thr->work);
  202. thr->state = state;
  203. thr->reply_queue = replyqueue;
  204. if (spawn_func(worker_thread_main, thr) < 0) {
  205. log_err(LD_GENERAL, "Can't launch worker thread.");
  206. return NULL;
  207. }
  208. return thr;
  209. }
  210. /**
  211. * Add an item of work to a single worker thread. See threadpool_queue_work(*)
  212. * for arguments.
  213. */
  214. static workqueue_entry_t *
  215. workerthread_queue_work(workerthread_t *worker,
  216. int (*fn)(void *, void *),
  217. void (*reply_fn)(void *),
  218. void *arg)
  219. {
  220. workqueue_entry_t *ent = workqueue_entry_new(fn, reply_fn, arg);
  221. tor_mutex_acquire(&worker->lock);
  222. ent->on_thread = worker;
  223. ent->pending = 1;
  224. TOR_TAILQ_INSERT_TAIL(&worker->work, ent, next_work);
  225. if (worker->waiting) /* XXXX inside or outside of lock?? */
  226. tor_cond_signal_one(&worker->condition);
  227. tor_mutex_release(&worker->lock);
  228. return ent;
  229. }
  230. /**
  231. * Queue an item of work for a thread in a thread pool. The function
  232. * <b>fn</b> will be run in a worker thread, and will receive as arguments the
  233. * thread's state object, and the provided object <b>arg</b>. It must return
  234. * one of WQ_RPL_REPLY, WQ_RPL_ERROR, or WQ_RPL_SHUTDOWN.
  235. *
  236. * Regardless of its return value, the function <b>reply_fn</b> will later be
  237. * run in the main thread when it invokes replyqueue_process(), and will
  238. * receive as its argument the same <b>arg</b> object. It's the reply
  239. * function's responsibility to free the work object.
  240. *
  241. * On success, return a workqueue_entry_t object that can be passed to
  242. * workqueue_entry_cancel(). On failure, return NULL.
  243. *
  244. * Note that because each thread has its own work queue, work items may not
  245. * be executed strictly in order.
  246. */
  247. workqueue_entry_t *
  248. threadpool_queue_work(threadpool_t *pool,
  249. int (*fn)(void *, void *),
  250. void (*reply_fn)(void *),
  251. void *arg)
  252. {
  253. workerthread_t *worker;
  254. tor_mutex_acquire(&pool->lock);
  255. /* Pick the next thread in random-access order. */
  256. worker = pool->threads[pool->next_for_work++];
  257. if (!worker) {
  258. tor_mutex_release(&pool->lock);
  259. return NULL;
  260. }
  261. if (pool->next_for_work >= pool->n_threads)
  262. pool->next_for_work = 0;
  263. tor_mutex_release(&pool->lock);
  264. return workerthread_queue_work(worker, fn, reply_fn, arg);
  265. }
  266. /**
  267. * Queue a copy of a work item for every thread in a pool. This can be used,
  268. * for example, to tell the threads to update some parameter in their states.
  269. *
  270. * Arguments are as for <b>threadpool_queue_work</b>, except that the
  271. * <b>arg</b> value is passed to <b>dup_fn</b> once per each thread to
  272. * make a copy of it.
  273. *
  274. * Return 0 on success, -1 on failure.
  275. */
  276. int
  277. threadpool_queue_for_all(threadpool_t *pool,
  278. void *(*dup_fn)(const void *),
  279. int (*fn)(void *, void *),
  280. void (*reply_fn)(void *),
  281. void *arg)
  282. {
  283. int i = 0;
  284. workerthread_t *worker;
  285. void *arg_copy;
  286. while (1) {
  287. tor_mutex_acquire(&pool->lock);
  288. if (i >= pool->n_threads) {
  289. tor_mutex_release(&pool->lock);
  290. return 0;
  291. }
  292. worker = pool->threads[i++];
  293. tor_mutex_release(&pool->lock);
  294. arg_copy = dup_fn ? dup_fn(arg) : arg;
  295. /* CHECK*/ workerthread_queue_work(worker, fn, reply_fn, arg_copy);
  296. }
  297. }
  298. /** Launch threads until we have <b>n</b>. */
  299. static int
  300. threadpool_start_threads(threadpool_t *pool, int n)
  301. {
  302. tor_mutex_acquire(&pool->lock);
  303. if (pool->n_threads < n)
  304. pool->threads = tor_realloc(pool->threads, sizeof(workerthread_t*)*n);
  305. while (pool->n_threads < n) {
  306. void *state = pool->new_thread_state_fn(pool->new_thread_state_arg);
  307. workerthread_t *thr = workerthread_new(state, pool->reply_queue);
  308. if (!thr) {
  309. tor_mutex_release(&pool->lock);
  310. return -1;
  311. }
  312. pool->threads[pool->n_threads++] = thr;
  313. }
  314. tor_mutex_release(&pool->lock);
  315. return 0;
  316. }
  317. /**
  318. * Construct a new thread pool with <b>n</b> worker threads, configured to
  319. * send their output to <b>replyqueue</b>. The threads' states will be
  320. * constructed with the <b>new_thread_state_fn</b> call, receiving <b>arg</b>
  321. * as its argument. When the threads close, they will call
  322. * <b>free_thread_state_fn</b> on their states.
  323. */
  324. threadpool_t *
  325. threadpool_new(int n_threads,
  326. replyqueue_t *replyqueue,
  327. void *(*new_thread_state_fn)(void*),
  328. void (*free_thread_state_fn)(void*),
  329. void *arg)
  330. {
  331. threadpool_t *pool;
  332. pool = tor_malloc_zero(sizeof(threadpool_t));
  333. tor_mutex_init(&pool->lock);
  334. pool->new_thread_state_fn = new_thread_state_fn;
  335. pool->new_thread_state_arg = arg;
  336. pool->free_thread_state_fn = free_thread_state_fn;
  337. pool->reply_queue = replyqueue;
  338. if (threadpool_start_threads(pool, n_threads) < 0) {
  339. tor_mutex_uninit(&pool->lock);
  340. tor_free(pool);
  341. return NULL;
  342. }
  343. return pool;
  344. }
  345. /** Return the reply queue associated with a given thread pool. */
  346. replyqueue_t *
  347. threadpool_get_replyqueue(threadpool_t *tp)
  348. {
  349. return tp->reply_queue;
  350. }
  351. /** Allocate a new reply queue. Reply queues are used to pass results from
  352. * worker threads to the main thread. Since the main thread is running an
  353. * IO-centric event loop, it needs to get woken up with means other than a
  354. * condition variable. */
  355. replyqueue_t *
  356. replyqueue_new(uint32_t alertsocks_flags)
  357. {
  358. replyqueue_t *rq;
  359. rq = tor_malloc_zero(sizeof(replyqueue_t));
  360. if (alert_sockets_create(&rq->alert, alertsocks_flags) < 0) {
  361. tor_free(rq);
  362. return NULL;
  363. }
  364. tor_mutex_init(&rq->lock);
  365. TOR_TAILQ_INIT(&rq->answers);
  366. return rq;
  367. }
  368. /**
  369. * Return the "read socket" for a given reply queue. The main thread should
  370. * listen for read events on this socket, and call replyqueue_process() every
  371. * time it triggers.
  372. */
  373. tor_socket_t
  374. replyqueue_get_socket(replyqueue_t *rq)
  375. {
  376. return rq->alert.read_fd;
  377. }
  378. /**
  379. * Process all pending replies on a reply queue. The main thread should call
  380. * this function every time the socket returned by replyqueue_get_socket() is
  381. * readable.
  382. */
  383. void
  384. replyqueue_process(replyqueue_t *queue)
  385. {
  386. if (queue->alert.drain_fn(queue->alert.read_fd) < 0) {
  387. /* XXXX complain! */
  388. }
  389. tor_mutex_acquire(&queue->lock);
  390. while (!TOR_TAILQ_EMPTY(&queue->answers)) {
  391. /* lock must be held at this point.*/
  392. workqueue_entry_t *work = TOR_TAILQ_FIRST(&queue->answers);
  393. TOR_TAILQ_REMOVE(&queue->answers, work, next_work);
  394. tor_mutex_release(&queue->lock);
  395. work->reply_fn(work->arg);
  396. workqueue_entry_free(work);
  397. tor_mutex_acquire(&queue->lock);
  398. }
  399. tor_mutex_release(&queue->lock);
  400. }