forked from PacktPublishing/C-Programming-for-Linux-Systems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstop-token.cpp
41 lines (33 loc) · 1.2 KB
/
stop-token.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
#include <iostream>
#include <syncstream>
#include <thread>
#include <array>
using namespace std::literals::chrono_literals;
int main() {
const auto worker{[](std::stop_token token, int num){
while (!token.stop_requested()) {
std::osyncstream{std::cout} << "Thread with id "
<< num
<< " is currently working.\n";
std::this_thread::sleep_for(200ms);
}
std::osyncstream{std::cout} << "Thread with id "
<< num
<< " is now stopped!\n";
}};
std::array<std::jthread, 3> my_threads{
std::jthread{worker, 0},
std::jthread{worker, 1},
std::jthread{worker, 2}
};
// Give some time to the other threads to start executing ...
std::this_thread::sleep_for(1s);
// Let's stop them
for (auto& thread : my_threads) {
thread.request_stop(); // this is not a blocking call,
// it is just a request.
}
std::osyncstream{std::cout} << "Main thread just requested stop!\n";
// jthread dtors join them here.
return 0;
}