-
Notifications
You must be signed in to change notification settings - Fork 0
/
safeQuque.h
93 lines (84 loc) · 2.36 KB
/
safeQuque.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#ifndef __SAFE_QUEUE__
#define __SAFE_QUEUE__
#pragma once
#include <queue>
#include <mutex>
#include <memory>
#include <condition_variable>
#include<chrono>
using clean_cb = void (*)(void* param);
namespace SAFE_STL {
template <typename T>
class s_queue {
private:
mutable std::mutex m_qmtx;
std::queue<T> m_native_queue;
std::condition_variable m_cond;
clean_cb m_cleancb;
public:
s_queue()
{
printf("SafeQueue default copy\n");
}
s_queue(s_queue const& other)
{
std::lock_guard<std::mutex> lk(other.m_qmtx);
m_native_queue = other.m_native_queue;
printf("SafeQueue copy copy\n");
}
~s_queue()
{
printf("SafeQueue ~SafeQueue:%s\n",m_native_queue.size());
while (m_native_queue.size()) {
auto data = std::move(m_native_queue.front());
m_native_queue.pop();
}
}
void push(T new_value)
{
std::lock_guard<std::mutex> lk(m_qmtx);
m_native_queue.push(std::move(new_value));
m_cond.notify_one();
}
std::shared_ptr<T> try_pop()
{
std::lock_guard<std::mutex> lk(m_qmtx);
if (m_native_queue.empty())
return std::shared_ptr<T>();
std::shared_ptr<T> res(std::make_shared<T>(m_native_queue.front()));
m_native_queue.pop();
return res;
}
std::shared_ptr<T> wait_and_pop(const unsigned int& milli_sec)
{
std::unique_lock<std::mutex> lk(m_qmtx);
if (m_native_queue.size() == 0) {
if (m_cond.wait_for(lk, std::chrono::milliseconds(milli_sec)) == std::cv_status::timeout) {
return std::shared_ptr<T>();
}
}
std::shared_ptr<T> res(std::make_shared<T>(m_native_queue.front()));
m_native_queue.pop();
return res;
}
std::shared_ptr<T> wait_and_pop()
{
std::unique_lock<std::mutex> lk(m_qmtx);
m_cond.wait(lk, [this] { return !m_native_queue.empty(); });
std::shared_ptr<T> res(std::make_shared<T>(m_native_queue.front()));
m_native_queue.pop();
return res;
}
bool empty() const
{
std::lock_guard<std::mutex> lk(m_qmtx);
return m_native_queue.empty();
}
bool front() const
{
std::lock_guard<std::mutex> lk(m_qmtx);
return m_native_queue.front();
}
};
}; // namespace SAFE_STL
#endif