forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_jthread.cpp
More file actions
44 lines (36 loc) · 1 KB
/
01_jthread.cpp
File metadata and controls
44 lines (36 loc) · 1 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
#include <chrono>
#include <cstdio>
#include <thread>
using namespace std::literals;
void non_interruptible_counter() {
int counter{0};
while (counter < 10) {
std::this_thread::sleep_for(0.2s);
printf("This is an non-interruptible thread. Counter: %d\n", counter);
++counter;
}
}
void interruptible_counter(std::stop_token token) {
int counter{0};
while (counter < 10) {
// Interupt Point!
if (token.stop_requested()) {
return;
}
std::this_thread::sleep_for(0.2s);
printf("This is an interruptible thread. Counter: %d\n", counter);
++counter;
}
}
int main() {
// No join() is needed!.
std::jthread thread1([]() { printf("Hello from jthread\n"); });
// Interruption Example
std::jthread non_interruptible_thread(non_interruptible_counter);
std::jthread interruptible_thread(
interruptible_counter); // Token is automatic
std::this_thread::sleep_for(1s);
non_interruptible_thread.request_stop();
interruptible_thread.request_stop();
return 0;
}