concurrent_queue.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #ifndef __CIRCULAR_QUEUE_H
  2. #define __CIRCULAR_QUEUE_H
  3. // This concurrent queue is thread safe if ...
  4. // if only one thread calls enque and only one thread calls dequeue.
  5. // This class is useful for one thread giving another thread a list of things to do.
  6. // The idea is that it's a linked list queue with always one empty node in it.
  7. // If front == back then the queue is empty. back always points to an empty node.
  8. // Because the two threads are adding and removing items from two different
  9. // ends of the linked list, it's "thread safe".
  10. template <class T>
  11. class concurrent_queue_node
  12. {
  13. public:
  14. T item;
  15. concurrent_queue_node<T> *next;
  16. };
  17. template <class T>
  18. class concurrent_queue
  19. {
  20. private:
  21. concurrent_queue_node<T> *front;
  22. concurrent_queue_node<T> *back; // Back always points to an empty node.
  23. public:
  24. concurrent_queue()
  25. {
  26. // There's always one item in the queue.
  27. // If front == back, then the queue is empty.
  28. front = new concurrent_queue_node<T>();
  29. front->next = nullptr;
  30. back = front;
  31. }
  32. bool empty()
  33. {
  34. return front == back;
  35. }
  36. void enqueue(T item)
  37. {
  38. concurrent_queue_node<T> *new_node;
  39. new_node = new concurrent_queue_node<T>();
  40. new_node->next = nullptr;
  41. back->item = item;
  42. back->next = new_node;
  43. back = new_node;
  44. return;
  45. }
  46. bool dequeue(T &item)
  47. {
  48. concurrent_queue_node<T> *item_to_delete;
  49. if (front == back) {
  50. return false;
  51. }
  52. item = front->item;
  53. item_to_delete = front;
  54. front = front->next;
  55. delete item_to_delete;
  56. return true;
  57. }
  58. ~concurrent_queue()
  59. {
  60. while (front != nullptr) {
  61. back = front;
  62. front = front->next;
  63. delete back;
  64. }
  65. }
  66. };
  67. #endif