queue.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "queue.h"
  2. #include "xalloc.h"
  3. #include <pthread.h>
  4. zqueue_t* queue_init()
  5. {
  6. zqueue_t *p = xmalloc(sizeof(zqueue_t));
  7. p->front = NULL;
  8. p->back = NULL;
  9. p->size = 0;
  10. pthread_mutex_init(&p->lock, NULL);
  11. pthread_cond_init(&p->empty, NULL);
  12. return p;
  13. }
  14. int is_empty(zqueue_t *queue)
  15. {
  16. return queue->size == 0;
  17. }
  18. void push_back(char* data, zqueue_t *queue)
  19. {
  20. znode_t *new_node = xmalloc(sizeof(znode_t));
  21. new_node->prev = NULL;
  22. new_node->next = NULL;
  23. new_node->data = strdup(data);
  24. pthread_mutex_lock(&queue->lock);
  25. if (is_empty(queue)) {
  26. queue->front = new_node;
  27. queue->back = new_node;
  28. } else {
  29. queue->back->next = new_node;
  30. new_node->prev = queue->back;
  31. queue->back = new_node;
  32. }
  33. queue->size++;
  34. pthread_cond_signal(&queue->empty);
  35. pthread_mutex_unlock(&queue->lock);
  36. }
  37. znode_t* pop_front(zqueue_t *queue)
  38. {
  39. pthread_mutex_lock(&queue->lock);
  40. while (is_empty(queue)) {
  41. pthread_cond_wait(&queue->empty, &queue->lock);
  42. }
  43. znode_t *temp = pop_front_unsafe(queue);
  44. pthread_mutex_unlock(&queue->lock);
  45. return temp;
  46. }
  47. znode_t* pop_front_unsafe(zqueue_t *queue)
  48. {
  49. znode_t *temp = queue->front;
  50. queue->front = temp->next;
  51. if (queue->front != NULL) {
  52. queue->front->prev = NULL;
  53. }
  54. queue->size--;
  55. return temp;
  56. }
  57. znode_t* get_front(zqueue_t *queue)
  58. {
  59. pthread_mutex_lock(&queue->lock);
  60. while (is_empty(queue)) {
  61. pthread_cond_wait(&queue->empty, &queue->lock);
  62. }
  63. znode_t *temp = xmalloc(sizeof(znode_t));
  64. temp = queue->front;
  65. pthread_mutex_unlock(&queue->lock);
  66. return temp;
  67. }
  68. znode_t* get_back(zqueue_t *queue)
  69. {
  70. pthread_mutex_lock(&queue->lock);
  71. while (is_empty(queue)) {
  72. pthread_cond_wait(&queue->empty, &queue->lock);
  73. }
  74. znode_t *temp = xmalloc(sizeof(znode_t));
  75. temp = queue->back;
  76. pthread_mutex_unlock(&queue->lock);
  77. return temp;
  78. }
  79. size_t get_size(zqueue_t *queue)
  80. {
  81. return queue->size;
  82. }