Advertisement
Guest User

Untitled

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