Advertisement
Guest User

Untitled

a guest
Nov 2nd, 2019
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <pthread.h>
  3. #include "queue.h"
  4.  
  5. typedef struct
  6. {
  7.     void **pitem;
  8.     int size, head, tail;
  9.  
  10.     pthread_mutex_t mutex;
  11.     pthread_cond_t empty, full;
  12. }
  13. queue_t;
  14.  
  15. void *queue_new(int size)
  16. {
  17.     queue_t *this = malloc(sizeof(queue_t));
  18.  
  19.     this->pitem = malloc(size * sizeof(void *));
  20.     this->size = size;
  21.     this->head = 0;
  22.     this->tail = 0;
  23.  
  24.     pthread_mutex_init(&this->mutex, NULL);
  25.     pthread_cond_init(&this->empty, NULL);
  26.     pthread_cond_init(&this->full, NULL);
  27.  
  28.     return this;
  29. }
  30.  
  31. void queue_free(void *_this)
  32. {
  33.     pthread_cond_destroy(&this->full);
  34.     pthread_cond_destroy(&this->empty);
  35.     pthread_mutex_destroy(&this->mutex);
  36.  
  37.     free(this->pitem)
  38.     free(this);
  39. }
  40.  
  41. #define QUEUE_EMPTY(this) (this->head == this->tail)
  42. #define QUEUE_FULL(this) ((this->tail + 1) % this->size == this->head)
  43.  
  44. void queue_add(void *_this, void *item)
  45. {
  46.     queue_t *this = _this;
  47.  
  48.     pthread_mutex_lock(this->mutex);
  49.  
  50.     if QUEUE_FULL(this) pthread_cond_wait(&this->full, &this->mutex);
  51.  
  52.     int empty = QUEUE_EMPTY(this);
  53.  
  54.     this->pitem[this->tail] = item;
  55.     this->tail = (this->tail + 1) % this->size;
  56.  
  57.     if (empty) pthread_cond_signal(this->empty);
  58.  
  59.     pthread_mutex_unlock(this->mutex);
  60. }
  61.  
  62. void *queue_remove(void *_this)
  63. {
  64.     queue_t *this = _this;
  65.  
  66.     pthread_mutex_lock(this->mutex);
  67.  
  68.     if QUEUE_EMPTY(this) pthread_cond_wait(&this->empty, &this->mutex);
  69.  
  70.     int full = QUEUE_FULL(this);
  71.  
  72.     void *ret = this->pitem[this->head];
  73.     this->head = (this->head + 1) % this->size;
  74.  
  75.     if (full) pthread_cond_signal(&this->full);
  76.  
  77.     pthread_mutex_unlock(this->mutex);
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement