-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAsync_02.cpp
More file actions
63 lines (48 loc) · 2.09 KB
/
Async_02.cpp
File metadata and controls
63 lines (48 loc) · 2.09 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
// ===========================================================================
// std::async // eager (std::launch::async) vs lazy (std::launch::deferred)
// ===========================================================================
#include "../Logger/Logger.h"
#include <chrono>
#include <future>
#include <iostream>
#include <string>
namespace EagerVsLazyASync {
static void test_01() {
Logger::log(std::cout, "Preparing calculations ...");
std::chrono::system_clock::time_point begin{ std::chrono::system_clock::now() };
std::future<std::chrono::system_clock::time_point> asyncLazy {
std::async(
std::launch::deferred,
[]() {
Logger::log(std::cout, "launch::deferred thread done!");
return std::chrono::system_clock::now();
}
)
};
std::future<std::chrono::system_clock::time_point> asyncEager{
std::async(
std::launch::async,
[] () {
Logger::log(std::cout, "launch::async thread done!");
return std::chrono::system_clock::now();
}
)
};
Logger::log(std::cout, "Now waiting for 5 seconds ...");
std::this_thread::sleep_for(std::chrono::seconds{ 5 });
std::chrono::system_clock::duration lazyStart{ asyncLazy.get() - begin };
std::chrono::system_clock::duration eagerStart{ asyncEager.get() - begin };
double lazyDuration{ std::chrono::duration<double>(lazyStart).count() };
double eagerDuration{ std::chrono::duration<double>(eagerStart).count() };
Logger::log(std::cout, "asyncLazy evaluated after : ", lazyDuration, " seconds.");
Logger::log(std::cout, "asyncEager evaluated after: ", eagerDuration, " seconds.");
}
}
void test_async_02()
{
using namespace EagerVsLazyASync;
test_01();
}
// ===========================================================================
// End-of-File
// ===========================================================================