-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path03_StopCallback.cpp
More file actions
76 lines (58 loc) · 2.25 KB
/
03_StopCallback.cpp
File metadata and controls
76 lines (58 loc) · 2.25 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// ===========================================================================
// StopCallback.cpp - std::stop_callback
// ===========================================================================
#include "../Logger/Logger.h"
#include <condition_variable>
#include <future>
#include <iostream>
#include <stop_token>
#include <thread>
// =============================================================================
// =============================================================================
namespace Using_Stop_Callbacks
{
static void task(std::stop_token token, int num)
{
Logger::log(std::cout, "Enter Task");
auto id{ std::this_thread::get_id() };
// register a stop callback
std::stop_callback cb{
token,
[=] {
auto currentId{ std::this_thread::get_id() };
if (currentId == id) {
Logger::log(std::cout, "Task: Stop requested - Thread Context = Task");
}
else {
Logger::log(std::cout, "Task: Stop requested - Thread Context = Main");
}
}
};
std::this_thread::sleep_for(std::chrono::seconds{ 3 });
Logger::log(std::cout, "Done Task");
}
static void test()
{
Logger::log(std::cout, "Main");
// create stop source and stop token
std::stop_source source;
std::stop_token token{ source.get_token() };
// A) request stop before task has been created
source.request_stop(); // put either this line into comment ...
std::future<void> future{
std::async(std::launch::async, [token] { task(token, 123); })
};
std::this_thread::sleep_for(std::chrono::seconds{ 2 });
// B) request stop after task has been created
// (runs any associated callbacks on this thread)
// source.request_stop(); // or put this line into comment
Logger::log(std::cout, "Done Main");
}
}
void test_stop_callback()
{
Using_Stop_Callbacks::test();
}
// ===========================================================================
// End-of-File
// ===========================================================================