Advertisement
Guest User

Untitled

a guest
Nov 3rd, 2019
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.61 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 cndput, cndtake;
  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->cndput, NULL);
  26.     pthread_cond_init(&this->cndtake, NULL);
  27.  
  28.     return this;
  29. }
  30.  
  31. void queue_free(void *_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.  
  58.     pthread_cond_signal(this->cndput);
  59. }
  60.  
  61. void *queue_take(void *_this)
  62. {
  63.     queue_t *this = _this;
  64.  
  65.     pthread_mutex_lock(this->mutex);
  66.  
  67.     while QUEUE_EMPTY(this)
  68.         pthread_cond_wait(&this->cndput, &this->mutex);
  69.  
  70.     void *ret = this->pitem[this->head];
  71.     this->head = (this->head + 1) % this->size;
  72.  
  73.     pthread_mutex_unlock(this->mutex);
  74.  
  75.     pthread_cond_signal(&this->cndtake);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement