-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththread_safe_queue.h
More file actions
50 lines (41 loc) · 1.04 KB
/
thread_safe_queue.h
File metadata and controls
50 lines (41 loc) · 1.04 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
#pragma once
#include <queue>
#include <mutex>
#include <condition_variable>
#include <utility>
template<class T>
class ThreadSafeQueue
{
public:
explicit ThreadSafeQueue(size_t capacity = 1000) : mCapacity{ capacity } {}
// Push an element. Block if queue is full.
void push(T&& elem);
// Pop an element and return a copy. Block if queue is empty.
T pop();
private:
std::mutex mMutex;
std::condition_variable mNotEmpty;
std::condition_variable mNotFull;
std::queue<T> mQueue;
const size_t mCapacity;
};
template<class T>
void ThreadSafeQueue<T>::push(T&& elem)
{
std::unique_lock<std::mutex> lck(mMutex);
mNotFull.wait(lck, [this] { return mQueue.size() < mCapacity; });
mQueue.push(std::forward<T>(elem));
lck.unlock();
mNotEmpty.notify_one();
}
template<class T>
T ThreadSafeQueue<T>::pop()
{
std::unique_lock<std::mutex> lck(mMutex);
mNotEmpty.wait(lck, [this] { return !mQueue.empty(); });
T elem = mQueue.front();
mQueue.pop();
lck.unlock();
mNotFull.notify_one();
return elem;
}