-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathqueue.cpp
More file actions
97 lines (76 loc) · 2.86 KB
/
Copy pathqueue.cpp
File metadata and controls
97 lines (76 loc) · 2.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <rsl/queue.hpp>
#include <catch2/catch_test_macros.hpp>
#include <array>
#include <atomic>
#include <thread>
#include <type_traits>
using namespace std::chrono_literals;
// NOLINTBEGIN(readability-container-size-empty)
TEST_CASE("rsl::Queue") {
SECTION("Type traits") {
STATIC_CHECK(!std::is_copy_constructible_v<rsl::Queue<int>>);
STATIC_CHECK(!std::is_copy_assignable_v<rsl::Queue<int>>);
STATIC_CHECK(!std::is_nothrow_move_constructible_v<rsl::Queue<int>>);
STATIC_CHECK(!std::is_nothrow_move_assignable_v<rsl::Queue<int>>);
}
SECTION("Default constructor") {
auto const queue = rsl::Queue<int>();
CHECK(queue.size() == 0);
CHECK(queue.empty());
}
SECTION("push()") {
auto queue = rsl::Queue<int>();
queue.push(42);
CHECK(queue.size() == 1);
CHECK(!queue.empty());
for (int i = 0; i < 99; ++i) queue.push(i);
CHECK(queue.size() == 100);
CHECK(!queue.empty());
}
SECTION("clear()") {
auto queue = rsl::Queue<int>();
for (int i = 0; i < 100; ++i) queue.push(i);
CHECK(queue.size() == 100);
CHECK(!queue.empty());
queue.clear();
CHECK(queue.size() == 0);
CHECK(queue.empty());
}
SECTION("pop()") {
SECTION("Sequentially") {
auto queue = rsl::Queue<int>();
CHECK(!queue.pop().has_value());
queue.push(999);
queue.push(1000);
CHECK(queue.pop(-1ms).value() == 999);
CHECK(queue.size() == 1);
CHECK(queue.pop().value() == 1000);
CHECK(queue.size() == 0);
CHECK(!queue.pop(1ms).has_value());
CHECK(queue.size() == 0);
}
SECTION("Concurrently") {
auto queue = rsl::Queue<int>();
constexpr auto thread_count = size_t(10);
constexpr auto item_count = size_t(100);
auto producers = std::array<std::thread, thread_count>();
for (auto& producer : producers) {
producer = std::thread([&queue] {
for (size_t i = 0; i < item_count; ++i) queue.push(int(i));
});
}
auto items_removed = std::atomic<size_t>(0);
auto consumers = std::array<std::thread, thread_count>();
for (auto& consumer : consumers) {
consumer = std::thread([&queue, &items_removed] {
for (size_t i = 0; i < item_count; ++i)
if (queue.pop(1ms).has_value()) ++items_removed;
});
}
for (auto& producer : producers) producer.join();
for (auto& consumer : consumers) consumer.join();
CHECK(queue.size() == thread_count * item_count - items_removed);
}
}
}
// NOLINTEND(readability-container-size-empty)