source: launchers/macosx/include/sharedqueue.h @ b40b987

Last change on this file since b40b987 was b40b987, checked in by meeh <meeh@…>, 3 years ago

Mac OSX Launcher:

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