-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathdemoex-async-future.cpp
More file actions
42 lines (27 loc) · 959 Bytes
/
Copy pathdemoex-async-future.cpp
File metadata and controls
42 lines (27 loc) · 959 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
41
42
/*
ASYNCHRONOUS PROGRAMMING WITH THE FUTURE
*/
#include <iostream>
#include <thread>
#include <future>
int main() {
// future from a packaged_task
std::packaged_task<int()> task([]{ return 7; }); // wrap the function
std::future<int> fut1 = task.get_future(); // get a future
std::thread th(std::move(task)); // launch on a thread
// future from an async()
std::future<int> fut2 = std::async(std::launch::async, []{ return 8; });
// future from a promise
std::promise<int> prom;
std::future<int> fut3 = prom.get_future();
std::thread( [&prom]{ prom.set_value_at_thread_exit(9); }).detach();
std::cout << "Waiting..." << std::endl;
fut1.wait();
fut2.wait();
fut3.wait();
th.join();
std::cout << "Done!" << std::endl;
std::cout << "Results are: "
<< fut1.get() << ' ' << fut2.get() << ' ' << fut3.get() << std::endl;
return 0;
}