-
Notifications
You must be signed in to change notification settings - Fork 206
/
main.cpp
42 lines (34 loc) · 1.12 KB
/
main.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
#include <iostream>
#include <thread>
#include <fstream>
#include <syncstream> // C++20
//#include <mutex> // for C++11 through C++17
//std::mutex write_mutex; // for C++11 through C++17
void worker(int start, int stop, std::ostream &os) {
for (int i = start; i < stop; ++i) {
// C++11 - C++17 solutions
// const std::lock_guard<std::mutex> lock{write_mutex}; // C++11
// const std::scoped_lock lock{write_mutex}; // C++17
// os << "thread: " << std::this_thread::get_id() << "; work: " << i;
// os << '\n';
// C++20 solution
std::osyncstream out{os};
out << "thread: " << std::this_thread::get_id() << "; work: " << i;
out << '\n';
}
}
void example(std::ostream &os) {
// jthread is C++20
std::jthread t1(worker, 10000, 20000, std::ref(os));
std::jthread t2(worker, 20000, 30000, std::ref(os));
// C++11 through C++17
// std::thread t1(worker, 10000, 20000, std::ref(os));
// std::thread t2(worker, 20000, 30000, std::ref(os));
// t2.join();
// t1.join();
}
int main() {
std::ofstream file{"out.txt"};
example(file);
return 0;
}