-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_unique_ptr_bool_example.cpp
More file actions
72 lines (55 loc) · 2.11 KB
/
thread_unique_ptr_bool_example.cpp
File metadata and controls
72 lines (55 loc) · 2.11 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
/**
* thread_unique_ptr_bool_example.cpp
*
* Here, I try to illustrate how threads can be controlled while they're
* running.
*
* In some cases, you want threads to be running in a loop until you tell them
* to stop. We can do this by sharing memory using an atomic boolean variable
* that tells threads if they're still running.
*
* It's especially important to make sure the while loop will reference the
* variable as `running->load()` otherwise the truthiness of `running` will
* always be true because it is a non-null shared pointer.
*
*/
#include <iostream>
#include <memory> // for std::unique_ptr
#include <thread>
#include <atomic>
#include <cstdio> // getchar
#include "expensive_resource.h"
int main() {
std::cout << "Starting main." << std::endl;
std::shared_ptr<std::atomic<bool>> running(new std::atomic<bool>(true));
// always use the actual object, not the pointer
// right now it's empty
std::unique_ptr<ExpensiveResource> resource;
resource = std::move(
std::unique_ptr<ExpensiveResource>(
new ExpensiveResource("resource1")));
std::thread thread1 = std::thread([res = std::move(resource), running]() {
std::cout << "Starting thread1." << std::endl;
while (running->load()) {
std::cout << "thread1 looping..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(600));
}
std::cout << "Ending thread1." << std::endl;
});
std::thread thread2 = std::thread([running]() {
std::cout << "Starting thread2." << std::endl;
ExpensiveResource localRes("resource2");
while (running->load()) {
std::cout << "thread2 looping..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(800));
}
std::cout << "Ending thread2." << std::endl;
});
std::cout << "(press enter to end the program)" << std::endl;
std::getchar();
std::cout << "(enter was pressed)" << std::endl;
running->store(false);
thread1.join();
thread2.join();
std::cout << "Ending main." << std::endl;
}