-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathmultithreading.cpp
44 lines (35 loc) · 1 KB
/
multithreading.cpp
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
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <thread>
#include <utility>
#include "msd/channel.hpp"
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>& ch, std::size_t i) {
for (auto number : ch) {
std::cout << number << " from thread: " << i << '\n';
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 in = [](msd::channel<std::int64_t>& ch) {
while (true) {
static std::int64_t i = 0;
ch << ++i;
}
};
auto write = std::thread{in, std::ref(channel)};
// Join all threads
for (std::size_t i = 0U; i < threads; ++i) {
reads.at(i).join();
}
write.join();
}