-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-thread.cc
84 lines (69 loc) · 2.41 KB
/
02-thread.cc
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
77
78
79
80
81
82
83
84
//
// Program
// This program simply creates a thread and calls different
// management functions.
//
// Compile
// g++ -Wall -Wextra -pedantic -std=c++17 -pthread -o 02-thread 02-thread.cc
//
// Execution
// ./02-thread
//
#include <iostream>
#include <iomanip>
#include <thread>
#include <ctime>
using namespace std::chrono;
//
// Function to be called for thread
//
static void thread_func(void) {
std::cout << __func__ << " is used by thread Id: " << std::this_thread::get_id() << '\n';
// ---------------------------------------
std::cout << '\n' << "--- sleep_for ---" << '\n';
{
auto time_cur = system_clock::to_time_t(system_clock::now());
auto time_str = std::put_time(std::localtime(&time_cur), "%H:%M:%S");
std::cout << "Going to sleep for 2s at " << time_str << '\n';
std::this_thread::sleep_for(2s);
time_cur = system_clock::to_time_t(system_clock::now());
time_str = std::put_time(std::localtime(&time_cur), "%H:%M:%S");
std::cout << "Back to live at " << time_str << '\n';
}
// ---------------------------------------
std::cout << '\n' << "--- sleep_until ---" << '\n';
{
auto time_cur = system_clock::to_time_t(system_clock::now());
auto time_str = std::put_time(std::localtime(&time_cur), "%H:%M:%S");
std::cout << "Going to sleep until for 3s at " << time_str << '\n';
std::this_thread::sleep_until(system_clock::now() + 3s);
time_cur = system_clock::to_time_t(system_clock::now());
time_str = std::put_time(std::localtime(&time_cur), "%H:%M:%S");
std::cout << "Back to live at " << time_str << '\n';
}
// ---------------------------------------
std::cout << '\n' << "--- yeild ---" << '\n';
{
auto time_cur = system_clock::to_time_t(system_clock::now());
auto time_str = std::put_time(std::localtime(&time_cur), "%H:%M:%S");
std::cout << "Going to yield at " << time_str << '\n';
std::this_thread::yield();
time_cur = system_clock::to_time_t(system_clock::now());
time_str = std::put_time(std::localtime(&time_cur), "%H:%M:%S");
std::cout << "Back to live at " << time_str << '\n';
}
}
//
// Entry function
//
int main() {
// Create & start thread
std::cout << "--- Thread: with managing functions ---" << '\n';
{
std::thread t(thread_func);
t.join(); // Wait for the thread until it completes its execution
}
// No thread is running at this moment
std::cout << "Good bye!" << '\n';
return 0;
}