-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSharedQueue.cpp
executable file
·65 lines (55 loc) · 1.44 KB
/
SharedQueue.cpp
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
//
// Created by Nolan Woods on 10/13/2018.
//
#include "SharedQueue.h"
template <typename T>
SharedQueue<T>::SharedQueue() : done(false) {}
template <typename T>
SharedQueue<T>::~SharedQueue() = default;
template <typename T>
T SharedQueue<T>::pop()
{
std::unique_lock<std::mutex> mlock(mutex_);
while (queue_.empty())
{
if (done) throw Stop();
cond_.wait(mlock);
}
T item = std::move(queue_.front());
//std::swap(item, queue_.front());
queue_.pop_front();
return item;
}
template <typename T>
void SharedQueue<T>::push(const T &item)
{
std::unique_lock<std::mutex> mlock(mutex_);
queue_.push_back(item);
mlock.unlock(); // unlock before notificiation to minimize mutex con
cond_.notify_one(); // notify one waiting thread
}
template <typename T>
void SharedQueue<T>::push(T &&item)
{
std::unique_lock<std::mutex> mlock(mutex_);
queue_.push_back(std::move(item));
mlock.unlock(); // unlock before notificiation to minimize mutex con
cond_.notify_one(); // notify one waiting thread
}
template <typename T>
void SharedQueue<T>::signal_done() {
this->done = true;
cond_.notify_all();
}
template <typename T>
unsigned long SharedQueue<T>::size(bool blocking)
{
if (blocking) {
std::unique_lock<std::mutex> mlock(mutex_);
unsigned long size = queue_.size();
mlock.unlock();
return size;
} else {
return queue_.size();
}
}