forked from mapmapteam/mapmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrentqueue.h
85 lines (74 loc) · 2.35 KB
/
concurrentqueue.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
/*
* Toonloop
*
* Copyright (c) 2010 Alexandre Quessy <[email protected]>
* Copyright (c) 2010 Tristan Matthews <[email protected]>
*
* Toonloop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Toonloop is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the gnu general public license
* along with Toonloop. If not, see <http://www.gnu.org/licenses/>.
*/
// Written by Anthony Williams, 2008
// Public domain based on his comment:
// "Yes, you can just copy the code presented here and use it for whatever you
// like. There won't be any licensing issues. I'm glad you find it helpful."
// Reference:
// http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
#ifndef _CONCURRENT_QUEUE_H_
#define _CONCURRENT_QUEUE_H_
#include <queue>
#include <QMutex>
#include <QWaitCondition>
template<typename Data>
class ConcurrentQueue
{
private:
std::queue<Data> queue_;
QMutex mutex_;
QWaitCondition condition_;
public:
ConcurrentQueue() : queue_(), mutex_(), condition_()
{}
void push(Data const& data)
{
QMutexLocker locker(&mutex_);
queue_.push(data);
condition_.wakeOne();
}
bool empty() const
{
QMutexLocker locker(&mutex_);
return queue_.empty();
}
bool try_pop(Data& popped_value)
{
QMutexLocker locker(&mutex_);
if (queue_.empty())
{
return false;
}
popped_value = queue_.front();
queue_.pop();
return true;
}
void wait_and_pop(Data& popped_value)
{
QMutexLocker locker(&mutex_);
while (queue_.empty())
{
condition_.wait(&mutex_);
}
popped_value = queue_.front();
queue_.pop();
}
};
#endif // _CONCURRENT_QUEUE_H_