Advertisement
techno-

queue.c con productores

Mar 2nd, 2023
123
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 <threads.h>
  3. #include "queue.h"
  4.  
  5. // circular array
  6. typedef struct _queue {
  7.     int size;
  8.     int used;
  9.     int first;
  10.     void **data;
  11.     mtx_t * mutex;
  12.     cnd_t * full;
  13.     cnd_t * empty;
  14. } _queue;
  15.  
  16. cnd_t *q_full(queue q){
  17.     return q->full;
  18. }
  19.  
  20. cnd_t *q_empty(queue q){
  21.     return q->empty;
  22. }
  23.  
  24. mtx_t * q_mutex(queue q){
  25.     return q->mutex;
  26. }
  27.  
  28. int q_size(queue q){
  29.     return q->size;
  30. }
  31.  
  32. queue q_create(int size) {
  33.     queue q = malloc(sizeof(_queue));
  34.  
  35.     q->size  = size;
  36.     q->used  = 0;
  37.     q->first = 0;
  38.     q->data  = malloc(size * sizeof(void *));
  39.     q->mutex = malloc(sizeof (mtx_t));
  40.     q->full= malloc(sizeof (cnd_t));
  41.     q->empty= malloc(sizeof (cnd_t));
  42.     mtx_init(q->mutex, mtx_plain);
  43.     cnd_init(q->full);
  44.     cnd_init(q->empty);
  45.  
  46.     return q;
  47. }
  48.  
  49. int q_elements(queue q) {
  50.     mtx_lock(q->mutex);
  51.     int res= q->used;
  52.     mtx_unlock(q->mutex);
  53.     return res;
  54. }
  55.  
  56. int q_insert(queue q, void *elem) {
  57.     mtx_lock(q->mutex);
  58.     if(q->size == q->used) return -1;
  59.  
  60.     q->data[(q->first + q->used) % q->size] = elem;
  61.     q->used++;
  62.     mtx_unlock(q->mutex);
  63.  
  64.     return 0;
  65. }
  66.  
  67. void *q_remove(queue q) {
  68.     void *res;
  69.     mtx_lock(q->mutex);
  70.     if(q->used == 0) return NULL;
  71.  
  72.     res = q->data[q->first];
  73.  
  74.     q->first = (q->first + 1) % q->size;
  75.     q->used--;
  76.  
  77.     mtx_unlock(q->mutex);
  78.     return res;
  79. }
  80.  
  81. void q_destroy(queue q) {
  82.     cnd_destroy(q->full);
  83.     cnd_destroy(q->empty);
  84.     mtx_destroy(q->mutex);
  85.     free(q->full);
  86.     free(q->empty);
  87.     free(q->mutex);
  88.     free(q->data);
  89.     free(q);
  90. }
  91.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement