-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_threadsafe_queue.cpp
More file actions
84 lines (69 loc) · 1.73 KB
/
test_threadsafe_queue.cpp
File metadata and controls
84 lines (69 loc) · 1.73 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
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
#include <cassert>
#include "threadsafe_queue.hpp"
void test_single_thread() {
ThreadSafeQueue<int> q;
assert(q.empty());
q.push(42);
assert(!q.empty());
int val;
assert(q.try_pop(val));
assert(val == 42);
assert(q.empty());
}
void test_multi_producer_consumer() {
ThreadSafeQueue<int> q;
std::atomic<int> counter{0};
const int N = 1000;
auto producer = [&] {
for (int i = 0; i < N; ++i) {
q.push(i);
counter++;
}
};
auto consumer = [&] {
int val;
while (counter < N || !q.empty()) {
if (q.try_pop(val)) {
assert(val >= 0 && val < N);
}
}
};
std::vector<std::thread> producers(4);
std::vector<std::thread> consumers(4);
for (auto& t : producers) t = std::thread(producer);
for (auto& t : consumers) t = std::thread(consumer);
for (auto& t : producers) t.join();
for (auto& t : consumers) t.join();
}
void test_wait_and_pop() {
ThreadSafeQueue<std::string> q;
std::atomic<bool> ready{false};
auto producer = [&] {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
q.push("data");
ready = true;
};
auto consumer = [&] {
std::string s;
q.wait_and_pop(s);
assert(ready && s == "data");
};
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
}
int main() {
test_single_thread();
test_multi_producer_consumer();
test_wait_and_pop();
std::cout << "All tests passed!\n";
return 0;
}
/*
g++ -std=c++11 -pthread test_threadsafe_queue.cpp -o test_queue
*/