-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessageQueue.h
More file actions
54 lines (48 loc) · 1.72 KB
/
messageQueue.h
File metadata and controls
54 lines (48 loc) · 1.72 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
#pragma once
#include <queue>
#include <condition_variable>
#include <mutex>
/////////////////////////////////////////////////////////////////////////////
// Name: messageQueue.h
// Purpose: messageQueue: Simple Message Queue for intra-thread communication
// Author: Mohd Radzi Ibrahim
// Modified by:
// Created: 13 July 2020
// Copyright: (c) MR Ibrahim
// Licence: GNU GENERAL PUBLIC LICENSE
/////////////////////////////////////////////////////////////////////////////
template<typename T>
class MessageQueue {
std::mutex mtxCond;
std::condition_variable cond;
std::queue<T> queue;
std::mutex mtxQueue;
bool isReady;
public:
MessageQueue() : isReady(false) {}
MessageQueue(const MessageQueue&) = delete;
MessageQueue& operator=(const MessageQueue&) = delete;
void Send(const T& item) {
mtxQueue.lock();
queue.push(item);
mtxQueue.unlock();
mtxCond.lock();
isReady = true; // this is to guard against 'spurious' signal;
mtxCond.unlock();
cond.notify_one();
}
bool Receive(T& item, size_t = 0) {
std::lock_guard<std::mutex> _lock(mtxQueue);
if (queue.empty()) {
return false;
}
std::unique_lock<std::mutex> lock(mtxCond);
cond.wait(lock, [&]() { return isReady; }); // this will loop waiting and locking and unlocking the mtxCond;
// until isReady is true; why? Because sometime Receive may be call before anybody sends
// when return, the lock is remained locked.
item = queue.front();
queue.pop();
lock.unlock();
return true;
}
};