Last change
on this file since ba853a8c was
d6fc0adb,
checked in by meeh <meeh@…>, 2 years ago
|
Mac OSX Launcher: Removed dmgconfig.py, added public domain to sharedqueue.h and updated xcode for the dmgconfig.py removal.
|
-
Property mode set to
100644
|
File size:
1.6 KB
|
Line | |
---|
1 | #ifndef SHAREDQUEUE_H__ |
---|
2 | #define SHAREDQUEUE_H__ |
---|
3 | // Public domain |
---|
4 | |
---|
5 | #include <queue> |
---|
6 | #include <mutex> |
---|
7 | #include <exception> |
---|
8 | #include <condition_variable> |
---|
9 | |
---|
10 | /** Multiple producer, multiple consumer thread safe queue |
---|
11 | * Since 'return by reference' is used this queue won't throw */ |
---|
12 | template<typename T> |
---|
13 | class shared_queue |
---|
14 | { |
---|
15 | std::queue<T> queue_; |
---|
16 | mutable std::mutex m_; |
---|
17 | std::condition_variable data_cond_; |
---|
18 | |
---|
19 | shared_queue& operator=(const shared_queue&); |
---|
20 | shared_queue(const shared_queue& other); |
---|
21 | |
---|
22 | public: |
---|
23 | shared_queue(){} |
---|
24 | |
---|
25 | void push(T item){ |
---|
26 | { |
---|
27 | std::lock_guard<std::mutex> lock(m_); |
---|
28 | queue_.push(item); |
---|
29 | } |
---|
30 | data_cond_.notify_one(); |
---|
31 | } |
---|
32 | |
---|
33 | /// \return immediately, with true if successful retrieval |
---|
34 | bool try_and_pop(T& popped_item){ |
---|
35 | std::lock_guard<std::mutex> lock(m_); |
---|
36 | if(queue_.empty()){ |
---|
37 | return false; |
---|
38 | } |
---|
39 | popped_item=std::move(queue_.front()); |
---|
40 | queue_.pop(); |
---|
41 | return true; |
---|
42 | } |
---|
43 | |
---|
44 | /// Try to retrieve, if no items, wait till an item is available and try again |
---|
45 | void wait_and_pop(T& popped_item){ |
---|
46 | std::unique_lock<std::mutex> lock(m_); // note: unique_lock is needed for std::condition_variable::wait |
---|
47 | while(queue_.empty()) |
---|
48 | { // The 'while' loop below is equal to |
---|
49 | data_cond_.wait(lock); //data_cond_.wait(lock, [](bool result){return !queue_.empty();}); |
---|
50 | } |
---|
51 | popped_item=std::move(queue_.front()); |
---|
52 | queue_.pop(); |
---|
53 | } |
---|
54 | |
---|
55 | bool empty() const{ |
---|
56 | std::lock_guard<std::mutex> lock(m_); |
---|
57 | return queue_.empty(); |
---|
58 | } |
---|
59 | |
---|
60 | unsigned size() const{ |
---|
61 | std::lock_guard<std::mutex> lock(m_); |
---|
62 | return queue_.size(); |
---|
63 | } |
---|
64 | }; |
---|
65 | |
---|
66 | #endif // SHAREDQUEUE_H__ |
---|
Note: See
TracBrowser
for help on using the repository browser.