Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <threads.h>
- #include "queue.h"
- // circular array
- typedef struct _queue {
- int size;
- int used;
- int first;
- void **data;
- mtx_t * mutex;
- cnd_t * full;
- cnd_t * empty;
- } _queue;
- cnd_t *q_full(queue q){
- return q->full;
- }
- cnd_t *q_empty(queue q){
- return q->empty;
- }
- mtx_t * q_mutex(queue q){
- return q->mutex;
- }
- int q_size(queue q){
- return q->size;
- }
- queue q_create(int size) {
- queue q = malloc(sizeof(_queue));
- q->size = size;
- q->used = 0;
- q->first = 0;
- q->data = malloc(size * sizeof(void *));
- q->mutex = malloc(sizeof (mtx_t));
- q->full= malloc(sizeof (cnd_t));
- q->empty= malloc(sizeof (cnd_t));
- mtx_init(q->mutex, mtx_plain);
- cnd_init(q->full);
- cnd_init(q->empty);
- return q;
- }
- int q_elements(queue q) {
- mtx_lock(q->mutex);
- int res= q->used;
- mtx_unlock(q->mutex);
- return res;
- }
- int q_insert(queue q, void *elem) {
- mtx_lock(q->mutex);
- if(q->size == q->used) return -1;
- q->data[(q->first + q->used) % q->size] = elem;
- q->used++;
- mtx_unlock(q->mutex);
- return 0;
- }
- void *q_remove(queue q) {
- void *res;
- mtx_lock(q->mutex);
- if(q->used == 0) return NULL;
- res = q->data[q->first];
- q->first = (q->first + 1) % q->size;
- q->used--;
- mtx_unlock(q->mutex);
- return res;
- }
- void q_destroy(queue q) {
- cnd_destroy(q->full);
- cnd_destroy(q->empty);
- mtx_destroy(q->mutex);
- free(q->full);
- free(q->empty);
- free(q->mutex);
- free(q->data);
- free(q);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement