| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
#pragma once |
| 22 |
|
| 23 |
#include <condition_variable> |
| 24 |
#include <list> |
| 25 |
#include <mutex> |
| 26 |
|
| 27 |
namespace Utils |
| 28 |
{ |
| 29 |
template<class T> |
| 30 |
class ThreadSafeQueue |
| 31 |
{ |
| 32 |
public: |
| 33 |
inline ThreadSafeQueue() |
| 34 |
: list(), |
| 35 |
mutex(), |
| 36 |
run(true) |
| 37 |
{ |
| 38 |
} |
| 39 |
|
| 40 |
inline ~ThreadSafeQueue() |
| 41 |
{ |
| 42 |
Terminate(); |
| 43 |
} |
| 44 |
|
| 45 |
inline void EnqueueBack(T t) |
| 46 |
{ |
| 47 |
std::unique_lock<std::mutex> lock(mutex); |
| 48 |
list.push_back(t); |
| 49 |
cv.notify_all(); |
| 50 |
} |
| 51 |
|
| 52 |
inline void EnqueueFront(T t) |
| 53 |
{ |
| 54 |
std::unique_lock<std::mutex> lock(mutex); |
| 55 |
list.push_front(t); |
| 56 |
cv.notify_all(); |
| 57 |
} |
| 58 |
|
| 59 |
T Dequeue() |
| 60 |
{ |
| 61 |
std::unique_lock<std::mutex> lock(mutex); |
| 62 |
while (list.empty()) |
| 63 |
{ |
| 64 |
if (run == false) |
| 65 |
{ |
| 66 |
return T(); |
| 67 |
} |
| 68 |
cv.wait_for(lock, std::chrono::seconds(1)); |
| 69 |
} |
| 70 |
T val = list.front(); |
| 71 |
list.pop_front(); |
| 72 |
return val; |
| 73 |
} |
| 74 |
|
| 75 |
inline bool IsEmpty() |
| 76 |
{ |
| 77 |
std::unique_lock<std::mutex> lock(mutex); |
| 78 |
return list.empty(); |
| 79 |
} |
| 80 |
|
| 81 |
inline void Terminate() |
| 82 |
{ |
| 83 |
run = false; |
| 84 |
cv.notify_all(); |
| 85 |
} |
| 86 |
|
| 87 |
private: |
| 88 |
std::list<T> list; |
| 89 |
mutable std::mutex mutex; |
| 90 |
std::condition_variable cv; |
| 91 |
volatile bool run; |
| 92 |
}; |
| 93 |
} |