Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <pthread.h>
- #include "queue.h"
- typedef struct
- {
- void **pitem;
- int size, head, tail;
- pthread_mutex_t mutex;
- pthread_cond_t empty, full;
- }
- queue_t;
- void *queue_new(int size)
- {
- queue_t *this = malloc(sizeof(queue_t));
- this->pitem = malloc(size * sizeof(void *));
- this->size = size;
- this->head = 0;
- this->tail = 0;
- pthread_mutex_init(&this->mutex, NULL);
- pthread_cond_init(&this->empty, NULL);
- pthread_cond_init(&this->full, NULL);
- return this;
- }
- void queue_free(void *_this)
- {
- pthread_cond_destroy(&this->full);
- pthread_cond_destroy(&this->empty);
- pthread_mutex_destroy(&this->mutex);
- free(this->pitem)
- free(this);
- }
- #define QUEUE_EMPTY(this) (this->head == this->tail)
- #define QUEUE_FULL(this) ((this->tail + 1) % this->size == this->head)
- void queue_add(void *_this, void *item)
- {
- queue_t *this = _this;
- pthread_mutex_lock(this->mutex);
- if QUEUE_FULL(this) pthread_cond_wait(&this->full, &this->mutex);
- int empty = QUEUE_EMPTY(this);
- this->pitem[this->tail] = item;
- this->tail = (this->tail + 1) % this->size;
- if (empty) pthread_cond_signal(this->empty);
- pthread_mutex_unlock(this->mutex);
- }
- void *queue_remove(void *_this)
- {
- queue_t *this = _this;
- pthread_mutex_lock(this->mutex);
- if QUEUE_EMPTY(this) pthread_cond_wait(&this->empty, &this->mutex);
- int full = QUEUE_FULL(this);
- void *ret = this->pitem[this->head];
- this->head = (this->head + 1) % this->size;
- if (full) pthread_cond_signal(&this->full);
- pthread_mutex_unlock(this->mutex);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement