-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessageQueue.cpp
105 lines (83 loc) · 2.27 KB
/
MessageQueue.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
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
94
95
96
97
98
99
100
101
102
103
104
105
// File: MessageQueue.cpp
// Author: Seongdo Kim
// Contact: [email protected]
//
// Copyright (c) 2017, Seongdo Kim <[email protected]>
// All rights reserved.
// The copyright to the computer program(s) herein is
// the property of Seongdo Kim. The program(s) may be
// used and/or copied only with the written permission
// of Seongdo Kim or in accordance with the terms and
// conditions stipulated in the agreement/contract under
// which the program(s) have been supplied.
//
// Written by Seongdo Kim <[email protected]>, June, 2017
//
#include "MessageQueue.h"
#include "IOUtils.h"
#include <iostream>
using namespace seevider;
MessageQueue::MessageQueue() {
std::cout << std::endl << "----------<<< MessageQueue.cpp in >>>----------" << std::endl << std::endl;
}
MessageQueue::~MessageQueue() {
}
/**
* Push data into the concurrent queue
*/
void MessageQueue::push(std::unique_ptr<IMessageData> &data) {
boost::mutex::scoped_lock lock(mMutex);
if (mQueue.size() >= mMaxSize) {
if (data->save(mDataStorageFolder)) {
mNumStoredData++;
}
}
else { // memory is enough
mQueue.push(std::move(data));
}
lock.unlock();
mConditionVariable.notify_one();
}
bool MessageQueue::try_pop(std::unique_ptr<IMessageData> &data) {
boost::mutex::scoped_lock lock(mMutex);
loadStoredData();
if (mQueue.empty()) {
data = NULL;
return false;
}
data = std::move(mQueue.front());
mQueue.pop();
return true;
}
void MessageQueue::wait_and_pop(std::unique_ptr<IMessageData> &data) {
boost::mutex::scoped_lock lock(mMutex);
loadStoredData();
while (mQueue.empty()) {
mConditionVariable.wait(lock);
}
data = std::move(mQueue.front());
mQueue.pop();
}
void MessageQueue::pop() {
boost::mutex::scoped_lock lock(mMutex);
mQueue.pop();
}
bool MessageQueue::empty() const {
boost::mutex::scoped_lock lock(mMutex);
return mQueue.empty();
}
std::string MessageQueue::toString() const {
std::stringstream output;
boost::mutex::scoped_lock lock(mMutex);
output << "#Contents: " << mQueue.size();
return output.str();
}
void MessageQueue::loadStoredData() {
if (mQueue.size() < mMaxSize && mNumStoredData > 0) {
std::unique_ptr<IMessageData> storedData;
if (utils::loadMessage(storedData, mDataStorageFolder)) {
mQueue.push(std::move(storedData));
mNumStoredData--;
}
}
}