parent
689cf27fe9
commit
23d4263c71
@ -1,83 +1,75 @@ |
||||
|
||||
#ifndef SAFE_QUEUE_H |
||||
#define SAFE_QUEUE_H |
||||
#ifndef PACKET_QUEUE_H |
||||
#define PACKET_QUEUE_H |
||||
|
||||
#include <queue> |
||||
#include <thread> |
||||
|
||||
using namespace std; |
||||
|
||||
template<typename T> |
||||
class PacketQueue { |
||||
typedef void (*ReleaseCallback)(T &); |
||||
|
||||
typedef void (*SyncHandle)(queue<T> &); |
||||
|
||||
public: |
||||
|
||||
void push(T new_value) { |
||||
lock_guard<mutex> lk(mt); |
||||
if (running) { |
||||
q.push(new_value); |
||||
cv.notify_one(); |
||||
std::lock_guard<std::mutex> lk(m_mutex); |
||||
if (m_running) { |
||||
m_queue.push(new_value); |
||||
m_cond.notify_one(); |
||||
} |
||||
} |
||||
|
||||
int pop(T &value) { |
||||
int ret = 0; |
||||
unique_lock<mutex> lk(mt); |
||||
if (!running) { |
||||
std::unique_lock<std::mutex> lk(m_mutex); |
||||
if (!m_running) { |
||||
return ret; |
||||
} |
||||
if (!q.empty()) { |
||||
value = q.front(); |
||||
q.pop(); |
||||
if (!m_queue.empty()) { |
||||
value = m_queue.front(); |
||||
m_queue.pop(); |
||||
ret = 1; |
||||
} |
||||
return ret; |
||||
} |
||||
|
||||
void setRunning(bool run) { |
||||
lock_guard<mutex> lk(mt); |
||||
this->running = run; |
||||
std::lock_guard<std::mutex> lk(m_mutex); |
||||
m_running = run; |
||||
} |
||||
|
||||
int empty() { |
||||
return q.empty(); |
||||
std::lock_guard<std::mutex> lk(m_mutex); |
||||
return m_queue.empty(); |
||||
} |
||||
|
||||
int size() { |
||||
return static_cast<int>(q.size()); |
||||
std::lock_guard<std::mutex> lk(m_mutex); |
||||
return static_cast<int>(m_queue.size()); |
||||
} |
||||
|
||||
void clear() { |
||||
lock_guard<mutex> lk(mt); |
||||
int size = q.size(); |
||||
std::lock_guard<std::mutex> lk(m_mutex); |
||||
int size = m_queue.size(); |
||||
for (int i = 0; i < size; ++i) { |
||||
T value = q.front(); |
||||
T value = m_queue.front(); |
||||
releaseCallback(value); |
||||
q.pop(); |
||||
m_queue.pop(); |
||||
} |
||||
} |
||||
|
||||
void sync() { |
||||
lock_guard<mutex> lk(mt); |
||||
syncHandle(q); |
||||
} |
||||
|
||||
void setReleaseCallback(ReleaseCallback r) { |
||||
releaseCallback = r; |
||||
void setReleaseCallback(ReleaseCallback callback) { |
||||
releaseCallback = callback; |
||||
} |
||||
|
||||
private: |
||||
|
||||
mutex mt; |
||||
condition_variable cv; |
||||
std::mutex m_mutex; |
||||
std::condition_variable m_cond; |
||||
std::queue<T> m_queue; |
||||
bool m_running; |
||||
|
||||
queue<T> q; |
||||
bool running; |
||||
ReleaseCallback releaseCallback; |
||||
SyncHandle syncHandle; |
||||
}; |
||||
|
||||
#endif |
||||
#endif // PACKET_QUEUE_H
|
||||
|
Loading…
Reference in new issue