A clone of btpd with my configuration changes.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
1.7 KiB

  1. #include <sys/types.h>
  2. #include <pthread.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include "btpd.h"
  6. struct td_cb {
  7. void (*cb)(void *);
  8. void *arg;
  9. BTPDQ_ENTRY(td_cb) entry;
  10. };
  11. BTPDQ_HEAD(td_cb_tq, td_cb);
  12. static int m_td_rd, m_td_wr;
  13. static struct event m_td_ev;
  14. static struct td_cb_tq m_td_cbs = BTPDQ_HEAD_INITIALIZER(m_td_cbs);
  15. static pthread_mutex_t m_td_lock;
  16. void
  17. td_acquire_lock(void)
  18. {
  19. pthread_mutex_lock(&m_td_lock);
  20. }
  21. void
  22. td_release_lock(void)
  23. {
  24. pthread_mutex_unlock(&m_td_lock);
  25. }
  26. void
  27. td_post(void (*fun)(void *), void *arg)
  28. {
  29. struct td_cb *cb = btpd_calloc(1, sizeof(*cb));
  30. cb->cb = fun;
  31. cb->arg = arg;
  32. BTPDQ_INSERT_TAIL(&m_td_cbs, cb, entry);
  33. }
  34. void
  35. td_post_end(void)
  36. {
  37. char c = '1';
  38. td_release_lock();
  39. write(m_td_wr, &c, sizeof(c));
  40. }
  41. static void
  42. td_cb(int fd, short type, void *arg)
  43. {
  44. char buf[1024];
  45. struct td_cb_tq tmpq = BTPDQ_HEAD_INITIALIZER(tmpq);
  46. struct td_cb *cb, *next;
  47. read(fd, buf, sizeof(buf));
  48. td_acquire_lock();
  49. BTPDQ_FOREACH_MUTABLE(cb, &m_td_cbs, entry, next)
  50. BTPDQ_INSERT_TAIL(&tmpq, cb, entry);
  51. BTPDQ_INIT(&m_td_cbs);
  52. td_release_lock();
  53. BTPDQ_FOREACH_MUTABLE(cb, &tmpq, entry, next) {
  54. cb->cb(cb->arg);
  55. free(cb);
  56. }
  57. }
  58. void
  59. td_init(void)
  60. {
  61. int err;
  62. int fds[2];
  63. if (pipe(fds) == -1) {
  64. btpd_err("Couldn't create thread callback pipe (%s).\n",
  65. strerror(errno));
  66. }
  67. m_td_rd = fds[0];
  68. m_td_wr = fds[1];
  69. if ((err = pthread_mutex_init(&m_td_lock, NULL)) != 0)
  70. btpd_err("Couldn't create mutex (%s).\n", strerror(err));
  71. event_set(&m_td_ev, m_td_rd, EV_READ|EV_PERSIST, td_cb, NULL);
  72. btpd_ev_add(&m_td_ev, NULL);
  73. }