-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync.cpp
More file actions
40 lines (30 loc) · 976 Bytes
/
async.cpp
File metadata and controls
40 lines (30 loc) · 976 Bytes
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
#include <future>
#include <iostream>
#include <string>
std::string helloFunction(const std::string &s) {
return "Hello C++11 from " + s + ".";
}
class HelloFunctionObject {
public:
std::string operator()(const std::string &s) const {
std::this_thread::sleep_for(std::chrono::seconds(2));
return "Hello C++11 from " + s + ".";
}
};
int main() {
std::cout << std::endl;
// 带函数的future
auto futureFunction = std::async(helloFunction, "function");
// 带函数对象的future
HelloFunctionObject helloFunctionObject;
auto futureFunctionObject =
std::async(helloFunctionObject, "function object");
// 带匿名函数的future
auto futureLambda = std::async(
[](const std::string &s) { return "Hello C++11 from " + s + "."; },
"lambda function");
std::cout << futureFunction.get() << "\n"
<< futureFunctionObject.get() << "\n"
<< futureLambda.get() << std::endl;
std::cout << std::endl;
}