You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

117 lines
2.6 KiB

  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2017-2020 KiCad Developers, see AUTHORS.txt for contributors.
  5. *
  6. * This program is free software: you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the
  8. * Free Software Foundation, either version 3 of the License, or (at your
  9. * option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful, but
  12. * WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #ifndef SYNC_QUEUE_H
  20. #define SYNC_QUEUE_H
  21. #include <mutex>
  22. #include <queue>
  23. /**
  24. * Synchronized, locking queue. Safe for multiple producer/multiple consumer environments with
  25. * nontrivial data (though bear in mind data needs to be copied in and out).
  26. */
  27. template <typename T>
  28. class SYNC_QUEUE
  29. {
  30. public:
  31. SYNC_QUEUE()
  32. {
  33. }
  34. /**
  35. * Push a value onto the queue.
  36. */
  37. void push( T const& aValue )
  38. {
  39. GUARD guard( m_mutex );
  40. m_queue.push( aValue );
  41. }
  42. /**
  43. * Move a value onto the queue. Useful for e.g. unique_ptr.
  44. */
  45. void move_push( T&& aValue )
  46. {
  47. GUARD guard( m_mutex );
  48. m_queue.push( std::move( aValue ) );
  49. }
  50. /**
  51. * Pop a value if the queue into the provided variable.
  52. *
  53. * If the queue is empty, the variable is not touched.
  54. *
  55. * @return true if a value was popped.
  56. */
  57. bool pop( T& aReceiver )
  58. {
  59. GUARD guard( m_mutex );
  60. if( m_queue.empty() )
  61. {
  62. return false;
  63. }
  64. else
  65. {
  66. aReceiver = std::move( m_queue.front() );
  67. m_queue.pop();
  68. return true;
  69. }
  70. }
  71. /**
  72. * Return true if the queue is empty.
  73. */
  74. bool empty() const
  75. {
  76. GUARD guard( m_mutex );
  77. return m_queue.empty();
  78. }
  79. /**
  80. * Return the size of the queue.
  81. */
  82. size_t size() const
  83. {
  84. GUARD guard( m_mutex );
  85. return m_queue.size();
  86. }
  87. /**
  88. * Clear the queue.
  89. */
  90. void clear()
  91. {
  92. GUARD guard( m_mutex );
  93. while( !m_queue.empty() )
  94. {
  95. m_queue.pop();
  96. }
  97. }
  98. private:
  99. typedef std::lock_guard<std::mutex> GUARD;
  100. std::queue<T> m_queue;
  101. mutable std::mutex m_mutex;
  102. };
  103. #endif // SYNC_QUEUE_H