Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <assert.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <pthread.h>
- #define EVQ_MAX 10
- #define EVQ_SIZ (EVQ_MAX - 1)
- struct evqueue {
- int ev[EVQ_MAX];
- int start;
- int end;
- pthread_mutex_t lock;
- pthread_cond_t cond;
- pthread_t task;
- };
- #define evq_diff(q) (((q)->end + 1) % EVQ_MAX)
- #define evq_full(q) ((q)->start == evq_diff(q))
- #define evq_empty(q) ((q)->start == (q)->end)
- void evq_signal(struct evqueue *q)
- {
- pthread_cond_signal(&q->cond);
- }
- void evq_init(struct evqueue *q, void *(*handler)(void *))
- {
- assert(q);
- assert(handler);
- q->start = q->end = 0;
- pthread_mutex_init(&q->lock, NULL);
- pthread_cond_init(&q->cond, NULL);
- pthread_create(&q->task, NULL, 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_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;
- }
- void *ev_handler(void *evq)
- {
- struct evqueue *evqp = evq;
- printf("Starting event handler\n");
- for (;;) {
- pthread_mutex_lock(&evqp->lock);
- while (evq_empty(evqp))
- pthread_cond_wait(&evqp->cond, &evqp->lock);
- pthread_mutex_unlock(&evqp->lock);
- printf("Handling event %d\n", evq_get(evqp));
- }
- }
- static struct evqueue evq;
- int main(void)
- {
- int i;
- evq_init(&evq, ev_handler);
- for (i = 0; i < 2000000 ; i++) {
- if (evq_put(&evq, i)) {
- puts("Full");
- usleep(20 * 1000);
- }
- evq_signal(&evq);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement