-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage_queue_tests.cpp
More file actions
76 lines (58 loc) · 1.86 KB
/
message_queue_tests.cpp
File metadata and controls
76 lines (58 loc) · 1.86 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "catch.hpp"
#include "message_queue.hpp"
#include <thread>
#include <chrono>
TEST_CASE("Simple try and pop", "[MessageQueue]") {
MessageQueue<int> queue;
// should be empty to begin with
REQUIRE(queue.empty());
// The first thread addes a number to the queue
std::thread th1([](MessageQueue<int>& q) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
while (q.empty()) {
q.push(7);
break;
}
}, std::ref(queue));
// the second thread enters in an event loop to pop that number
std::thread th2([](MessageQueue<int>& q) {
int expected;
// wait for something to be in the queue
while (!q.try_pop(expected)) {}
// at this point the expected value should be what was pushed in the other thread
REQUIRE(expected == 7);
REQUIRE(q.empty());
// should return false since nothing is in the queue
REQUIRE(!q.try_pop(expected));
}, std::ref(queue));
th1.join();
th2.join();
// After both threads have completed their tasks, the queue should be empty
REQUIRE(queue.empty());
}
TEST_CASE("Simple wait and pop", "[MessageQueue]") {
MessageQueue<int> queue;
// should be empty to begin with
REQUIRE(queue.empty());
// The first thread addes a number to the queue (wait to add it)
std::thread th1([](MessageQueue<int>& q) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
while (q.empty()) {
q.push(7);
break;
}
}, std::ref(queue));
// the second thread enters in an event loop to pop that number
std::thread th2([](MessageQueue<int>& q) {
int expected;
// wait for something to be in the queue
q.wait_pop(expected);
// at this point the expected value should be what was pushed in the other thread
REQUIRE(expected == 7);
REQUIRE(q.empty());
}, std::ref(queue));
th1.join();
th2.join();
// After both threads have completed their tasks, the queue should be empty
REQUIRE(queue.empty());
}