-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadqueue.h
More file actions
63 lines (55 loc) · 1.29 KB
/
Copy paththreadqueue.h
File metadata and controls
63 lines (55 loc) · 1.29 KB
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
/*
* threadqueue.h
*
* Created on: 2017年6月16日
* Author: zjbpoping
*/
#ifndef THREADQUEUE_H_
#define THREADQUEUE_H_
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
namespace ps {
/**
* \brief thread-safe queue allowing push and waited pop
*/
template<typename T> class ThreadsafeQueue {
public:
ThreadsafeQueue() { }
~ThreadsafeQueue() { }
/**
* \brief push an value into the end. threadsafe.
* \param new_value the value
*/
void Push(T new_value) {
mu_.lock();
queue_.push(std::move(new_value));
mu_.unlock();
cond_.notify_all();
}
/**
* \brief wait until pop an element from the beginning, threadsafe
* \param value the poped value
*/
void WaitAndPop(T* value) {
std::unique_lock<std::mutex> lk(mu_);
cond_.wait(lk, [this]{return !queue_.empty();});
*value = std::move(queue_.front());
queue_.pop();
}
private:
mutable std::mutex mu_;
std::queue<T> queue_;
std::condition_variable cond_;
};
} // namespace ps
// bool TryPop(T& value) {
// std::lock_guard<std::mutex> lk(mut);
// if(data_queue.empty())
// return false;
// value=std::move(data_queue.front());
// data_queue.pop();
// return true;
// }
#endif