GRUTinizer
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
ThreadsafeQueue.h
Go to the documentation of this file.
1 #ifndef _THREADSAFEQUEUE_H_
2 #define _THREADSAFEQUEUE_H_
3 
4 #include <cassert>
5 #include <iostream>
6 
7 #ifndef __CINT__
8 #include <atomic>
9 #include <chrono>
10 #include <condition_variable>
11 #include <mutex>
12 #include <queue>
13 #endif
14 
15 template<typename T>
17 public:
20  void Push(T obj);
21  int Pop(T& output, int millisecond_wait = 1000);
22 
23  size_t ItemsPushed();
24  size_t ItemsPopped();
25  size_t Size();
26 
27 private:
28 #ifndef __CINT__
29  std::mutex mutex;
30  std::queue<T> queue;
31  std::condition_variable can_push;
32  std::condition_variable can_pop;
33 
35 
37  size_t items_pushed;
38  size_t items_popped;
39 #endif
40 };
41 
42 #ifndef __CINT__
43 template<typename T>
45  : max_queue_size(10000),
46  items_in_queue(0), items_pushed(0), items_popped(0) { }
47 
48 template<typename T>
50 
51 template<typename T>
53  std::unique_lock<std::mutex> lock(mutex);
54  if(queue.size() > max_queue_size){
55  can_push.wait(lock);
56  }
57 
58  items_pushed++;
59  items_in_queue++;
60 
61  queue.push(obj);
62  can_pop.notify_one();
63 }
64 
65 template<typename T>
66 int ThreadsafeQueue<T>::Pop(T& output, int millisecond_wait) {
67  std::unique_lock<std::mutex> lock(mutex);
68  if(!queue.size()){
69  can_pop.wait_for(lock, std::chrono::milliseconds(millisecond_wait));
70  }
71 
72  if(!queue.size()){
73  return 1;
74  }
75 
76  output = queue.front();
77  queue.pop();
78 
79  items_popped++;
80  items_in_queue--;
81 
82  can_push.notify_one();
83  return 0;
84 }
85 
86 template<typename T>
88  std::unique_lock<std::mutex> lock(mutex);
89  return items_in_queue;
90 }
91 
92 template<typename T>
94  std::unique_lock<std::mutex> lock(mutex);
95  return items_pushed;
96 }
97 
98 template<typename T>
100  std::unique_lock<std::mutex> lock(mutex);
101  return items_popped;
102 }
103 #endif /* __CINT__ */
104 
105 #endif /* _THREADSAFEQUEUE_H_ */