Advertisement
danielhilst

evq.c

Apr 22nd, 2015
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. #include "evq.h"
  2.  
  3. void evq_signal(struct evqueue *q)
  4. {
  5.         pthread_cond_signal(&q->cond);
  6. }
  7.  
  8. int evq_get(struct evqueue *q)
  9. {
  10.         int ev;
  11.  
  12.         pthread_mutex_lock(&q->lock);
  13.         if (evq_empty(q)) {
  14.                 ev = -1;
  15.         } else {
  16.                 ev = q->ev[q->start];
  17.                 q->start = (q->start + 1) % EVQ_MAX;
  18.         }
  19.         pthread_mutex_unlock(&q->lock);
  20.         return ev;
  21. }
  22.  
  23. static void *evq_handler(void *evq)
  24. {
  25.         struct evqueue *evqp = evq;
  26.  
  27.         for (;;) {
  28.                 pthread_mutex_lock(&evqp->lock);
  29.                 while (evq_empty(evqp))
  30.                         pthread_cond_wait(&evqp->cond, &evqp->lock);
  31.                 pthread_mutex_unlock(&evqp->lock);
  32.  
  33.                 evqp->user_handler(evq_get(evqp));
  34.         }
  35.  
  36.         return NULL;
  37. }
  38.  
  39. void evq_init(struct evqueue *q, void (*handler)(int))
  40. {
  41.         assert(q);
  42.         assert(handler);
  43.  
  44.         q->start = q->end = 0;
  45.         q->user_handler = handler;
  46.         pthread_mutex_init(&q->lock, NULL);
  47.         pthread_cond_init(&q->cond, NULL);
  48.         pthread_create(&q->task, NULL, evq_handler, q);
  49. }
  50.  
  51. int evq_put(struct evqueue *q, int ev)
  52. {
  53.         int rc = 0;
  54.  
  55.         pthread_mutex_lock(&q->lock);
  56.         if (evq_full(q)) {
  57.                 rc = -1;
  58.         } else {
  59.                 q->ev[q->end] = ev;
  60.                 q->end = (q->end + 1) % EVQ_MAX;
  61.         }
  62.         pthread_mutex_unlock(&q->lock);
  63.         return rc;
  64. }
  65.  
  66. int evq_size(struct evqueue *q)
  67. {
  68.         int siz;
  69.  
  70.         pthread_mutex_lock(&q->lock);
  71.         siz = q->end - q->start;
  72.         if (siz < 0)
  73.                 siz += EVQ_MAX;
  74.         pthread_mutex_unlock(&q->lock);
  75.         return siz;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement