concurrency.hpp
Go to the documentation of this file.
1 // License: Apache 2.0. See LICENSE file in root directory.
2 // Copyright(c) 2015 Intel Corporation. All Rights Reserved.
3 
4 #include <queue>
5 #include <mutex>
6 #include <condition_variable>
7 #include <thread>
8 
9 // Simplest implementation of a blocking concurrent queue for thread messaging
10 template<class T>
12 {
13  std::queue<T> q;
14  std::mutex mutex;
15  std::condition_variable cv;
16 
17 public:
19 
20  void enqueue(T item)
21  {
22  std::unique_lock<std::mutex> lock(mutex);
23  q.push(std::move(item));
24  lock.unlock();
25  cv.notify_one();
26  }
27 
28  T dequeue()
29  {
30  std::unique_lock<std::mutex> lock(mutex);
31  const auto ready = [this]() { return !q.empty(); };
32  if (!ready() && !cv.wait_for(lock, std::chrono::seconds(5), ready)) throw std::runtime_error("Timeout waiting for queued items!");
33  auto item = std::move(q.front());
34  q.pop();
35  return std::move(item);
36  }
37 
38  bool try_dequeue(T* item)
39  {
40  std::unique_lock<std::mutex> lock(mutex);
41  if(q.size()>0)
42  {
43  auto val = std::move(q.front());
44  q.pop();
45  *item = std::move(val);
46  return true;
47  }
48  return false;
49  }
50 
51  void clear()
52  {
53  std::unique_lock<std::mutex> lock(mutex);
54  while (q.size() > 0)
55  {
56  const auto ready = [this]() { return !q.empty(); };
57  if (!ready() && !cv.wait_for(lock, std::chrono::seconds(5), ready)) throw std::runtime_error("Timeout waiting for queued items!");
58  auto item = std::move(q.front());
59  q.pop();
60  }
61 
62 
63  }
64  size_t size()
65  {
66  std::unique_lock<std::mutex> lock(mutex);
67  return q.size();
68  }
69 };
70 
71 inline bool any_costumers_alive(const std::vector<bool>& running)
72 {
73  for (auto is_running : running)
74  {
75  if (is_running)
76  {
77  return true;
78  }
79  }
80  return false;
81 }
void enqueue(T item)
Definition: concurrency.hpp:20
bool try_dequeue(T *item)
Definition: concurrency.hpp:38
GLfloat seconds
Definition: wglext.h:657
std::condition_variable cv
Definition: concurrency.hpp:15
std::queue< T > q
Definition: concurrency.hpp:13
bool any_costumers_alive(const std::vector< bool > &running)
Definition: concurrency.hpp:71
GLuint GLfloat * val
Definition: glext.h:1490


librealsense
Author(s): Sergey Dorodnicov , Mark Horn , Reagan Lopez
autogenerated on Fri Mar 13 2020 03:16:16