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.

114 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 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> class SYNC_QUEUE
  28. {
  29. typedef std::lock_guard<std::mutex> GUARD;
  30. std::queue<T> m_queue;
  31. mutable std::mutex m_mutex;
  32. public:
  33. SYNC_QUEUE()
  34. {
  35. }
  36. /**
  37. * Push a value onto the queue.
  38. */
  39. void push( T const& aValue )
  40. {
  41. GUARD guard( m_mutex );
  42. m_queue.push( aValue );
  43. }
  44. /**
  45. * Move a value onto the queue. Useful for e.g. unique_ptr.
  46. */
  47. void move_push( T&& aValue )
  48. {
  49. GUARD guard( m_mutex );
  50. m_queue.push( std::move( aValue ) );
  51. }
  52. /**
  53. * Pop a value off the queue into the provided variable. If the queue is empty, the
  54. * variable is not touched.
  55. *
  56. * @return true iff a value was popped.
  57. */
  58. bool pop( T& aReceiver )
  59. {
  60. GUARD guard( m_mutex );
  61. if( m_queue.empty() )
  62. {
  63. return false;
  64. }
  65. else
  66. {
  67. aReceiver = std::move( m_queue.front() );
  68. m_queue.pop();
  69. return true;
  70. }
  71. }
  72. /**
  73. * Return true iff the queue is empty.
  74. */
  75. bool empty() const
  76. {
  77. GUARD guard( m_mutex );
  78. return m_queue.empty();
  79. }
  80. /**
  81. * Return the size of the queue.
  82. */
  83. size_t size() const
  84. {
  85. GUARD guard( m_mutex );
  86. return m_queue.size();
  87. }
  88. /**
  89. * Clear the queue.
  90. */
  91. void clear()
  92. {
  93. GUARD guard( m_mutex );
  94. while( !m_queue.empty() )
  95. {
  96. m_queue.pop();
  97. }
  98. }
  99. };
  100. #endif // SYNC_QUEUE_H