Wildmeshing Toolkit
Loading...
Searching...
No Matches
concurrent_priority_queue.hpp
1#pragma once
2
3#include <deque>
4#include <mutex>
5#include <queue>
6
7namespace wmtk::threading {
8// ---------------------------------------------------------------------------
9// concurrent_priority_queue: replaces tbb::concurrent_priority_queue.
10// Max-heap by default, matching TBB. std::priority_queue + mutex.
11// Non-movable (holds a mutex); constructed in place inside std::vector(count).
12// ---------------------------------------------------------------------------
13template <typename T, typename Compare = std::less<T>>
15{
16 mutable std::mutex m_mutex;
17 // A deque underneath, not a vector. std::priority_queue runs the same push_heap /
18 // pop_heap index arithmetic on either, so the heap layout -- and the pop order -- is
19 // identical; what changes is that a deque grows in fixed blocks instead of doubling.
20 // The queues are at their largest on the first pass after construction, when the mesh is
21 // too, and a vector there both carried up to 2x unused capacity and, at each doubling,
22 // held the old and the new buffer at once.
23 std::priority_queue<T, std::deque<T>, Compare> m_queue;
24
25public:
26 concurrent_priority_queue() = default;
28 concurrent_priority_queue& operator=(const concurrent_priority_queue&) = delete;
29
30 bool try_pop(T& out)
31 {
32 std::lock_guard<std::mutex> lock(m_mutex);
33 if (m_queue.empty()) {
34 return false;
35 }
36 out = m_queue.top();
37 m_queue.pop();
38 return true;
39 }
40
41 void push(const T& v)
42 {
43 std::lock_guard<std::mutex> lock(m_mutex);
44 m_queue.push(v);
45 }
46
47 template <typename... Args>
48 void emplace(Args&&... args)
49 {
50 std::lock_guard<std::mutex> lock(m_mutex);
51 m_queue.emplace(std::forward<Args>(args)...);
52 }
53
54 std::size_t size() const
55 {
56 std::lock_guard<std::mutex> lock(m_mutex);
57 return m_queue.size();
58 }
59 bool empty() const
60 {
61 std::lock_guard<std::mutex> lock(m_mutex);
62 return m_queue.empty();
63 }
64};
65
66} // namespace wmtk::threading
Definition concurrent_priority_queue.hpp:15