-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathmultithreading.cpp
More file actions
46 lines (37 loc) · 1.11 KB
/
multithreading.cpp
File metadata and controls
46 lines (37 loc) · 1.11 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
#include <msd/channel.hpp>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <thread>
int main()
{
const auto threads = std::thread::hardware_concurrency();
msd::channel<std::int64_t> channel{threads};
// Read
const auto out = [](msd::channel<std::int64_t>& chan, const std::size_t value) {
for (auto number : chan) {
std::stringstream stream;
stream << number << " from thread: " << value << '\n';
std::cout << stream.str();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
};
std::vector<std::thread> reads;
for (std::size_t i = 0U; i < threads; ++i) {
reads.emplace_back(out, std::ref(channel), i);
}
// Write
const auto input = [](msd::channel<std::int64_t>& chan) {
while (true) {
static std::int64_t value = 0;
chan << ++value;
}
};
auto write = std::thread{input, std::ref(channel)};
// Join all threads
for (std::size_t i = 0U; i < threads; ++i) {
reads.at(i).join();
}
write.join();
}