Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "evq.h"
- void evq_signal(struct evqueue *q)
- {
- pthread_cond_signal(&q->cond);
- }
- int evq_get(struct evqueue *q)
- {
- int ev;
- pthread_mutex_lock(&q->lock);
- if (evq_empty(q)) {
- ev = -1;
- } else {
- ev = q->ev[q->start];
- q->start = (q->start + 1) % EVQ_MAX;
- }
- pthread_mutex_unlock(&q->lock);
- return ev;
- }
- static void *evq_handler(void *evq)
- {
- struct evqueue *evqp = evq;
- for (;;) {
- pthread_mutex_lock(&evqp->lock);
- while (evq_empty(evqp))
- pthread_cond_wait(&evqp->cond, &evqp->lock);
- pthread_mutex_unlock(&evqp->lock);
- evqp->user_handler(evq_get(evqp));
- }
- return NULL;
- }
- void evq_init(struct evqueue *q, void (*handler)(int))
- {
- assert(q);
- assert(handler);
- q->start = q->end = 0;
- q->user_handler = handler;
- pthread_mutex_init(&q->lock, NULL);
- pthread_cond_init(&q->cond, NULL);
- pthread_create(&q->task, NULL, evq_handler, q);
- }
- int evq_put(struct evqueue *q, int ev)
- {
- int rc = 0;
- pthread_mutex_lock(&q->lock);
- if (evq_full(q)) {
- rc = -1;
- } else {
- q->ev[q->end] = ev;
- q->end = (q->end + 1) % EVQ_MAX;
- }
- pthread_mutex_unlock(&q->lock);
- return rc;
- }
- int evq_size(struct evqueue *q)
- {
- int siz;
- pthread_mutex_lock(&q->lock);
- siz = q->end - q->start;
- if (siz < 0)
- siz += EVQ_MAX;
- pthread_mutex_unlock(&q->lock);
- return siz;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement