-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPackagedTask_01.cpp
More file actions
99 lines (74 loc) · 2.81 KB
/
PackagedTask_01.cpp
File metadata and controls
99 lines (74 loc) · 2.81 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// ===========================================================================
// PackagedTask_01.cpp // Packaged Task
// ===========================================================================
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
namespace PackagedTaskComparison {
// -----------------------------------------------------------------------
// demonstrating std::packaged_task with thread (asynchronous execution)
static void test_01() {
// create packaged_task object
std::packaged_task<int(void)> task{
[] () {
std::this_thread::sleep_for(std::chrono::seconds{ 1 });
return 123;
}
};
// retrieve future object from task
std::future<int> future{ task.get_future() };
// create a thread with this task
std::thread t{ std::move(task) };
// retrieve result from future object
int result{ future.get() };
std::cout << "Result: " << result << std::endl;
t.join();
}
// -----------------------------------------------------------------------
// demonstrating std::packaged_task without thread (synchronous execution)
static void test_02() {
// create packaged_task object
std::packaged_task<int(void)> task {
[] () {
std::this_thread::sleep_for(std::chrono::seconds{ 1 });
return 123;
}
};
// retrieve future object from task
std::future<int> future{ task.get_future() };
// execute task
task();
// retrieve result from future object
int result{ future.get() };
std::cout << "Result: " << result << std::endl;
}
// -----------------------------------------------------------------------
// equivalent code, demonstrating std::function and std::promise
static void test_03() {
std::promise<int> promise;
std::future<int> future{ promise.get_future() };
std::function<void(std::promise<int>&&)> function {
[] (std::promise<int>&& promise) {
std::this_thread::sleep_for(std::chrono::seconds{ 1 });
promise.set_value(123);
}
};
// create a thread with this function
std::thread t{ std::move(function), std::move(promise) };
// retrieve result from future object
int result = future.get();
std::cout << "Result: " << result << std::endl;
t.join();
}
}
void test_packaged_task_01 ()
{
using namespace PackagedTaskComparison;
test_01();
test_02();
test_03();
}
// ===========================================================================
// End-of-File
// ===========================================================================