-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.cpp
More file actions
executable file
·74 lines (57 loc) · 1.58 KB
/
thread.cpp
File metadata and controls
executable file
·74 lines (57 loc) · 1.58 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
#include <map>
#include <thread>
#include <string>
#include <iostream>
#include <unistd.h> // for "usleep"
// #include <chrono>
// using namespace std::chrono_literals; // for "ms"
using namespace std::literals::chrono_literals;
#define print(x) std::cout << x << std::endl
void func1() {
for (int i = 0; i < 10; i++) {
print("f1 :: " << i << "\n");
std::this_thread::sleep_for(0.9s);
}
}
void func2(std::string p) {
for (int i = 0; i < 10; i++) {
print(p << " :: " << i << "\n");
std::this_thread::sleep_for(0.9s);
}
}
void refresh(std::map<std::string, int>& forecast)
{
while (true) {
for (auto &item: forecast) {
item.second++;
print(item.first << " -> " << item.second);
}
// usleep(1 * 1000 * 1000);
std::this_thread::sleep_for(1s);
}
return;
}
int main()
{
std::map<std::string, int> forecast = {
{"Tokyo", 100},
{"Taipei", 200},
{"Berlin", 300}
};
// Start running worker1 here ...
std::thread worker1(func1);
std::thread worker2(func2, "-> f2");
usleep(1 * 1000 * 1000); // 1s
std::thread bgWorker(refresh, std::ref(forecast));
// ... but here worker1 and worker2 should wait for one loop execution of
// "bgWorker" and the next loop of worker1 and worker2 can keep running
bgWorker.join();
worker1.join();
worker2.join();
// Run the thread until the thread is "detach"ed.
// worker1.detach();
// worker2.detach();
// bgWorker.detach();
// system("pause>nul");
return 0;
}