Skip to content

Commit e005463

Browse files
authored
Update 003_std_thread_std_future.cpp
1 parent 4d0f902 commit e005463

1 file changed

Lines changed: 27 additions & 1 deletion

File tree

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,27 @@
1-
1
1+
#include <iostream>
2+
#include <future>
3+
#include <thread>
4+
5+
int main()
6+
{
7+
// future from a packaged_task
8+
std::packaged_task<int()> task([]{ return 7; }); // wrap the function
9+
std::future<int> f1 = task.get_future(); // get a future
10+
std::thread t(std::move(task)); // launch on a thread
11+
12+
// future from an async()
13+
std::future<int> f2 = std::async(std::launch::async, []{ return 8; });
14+
15+
// future from a promise
16+
std::promise<int> p;
17+
std::future<int> f3 = p.get_future();
18+
std::thread( [&p]{ p.set_value_at_thread_exit(9); }).detach();
19+
20+
std::cout << "Waiting..." << std::flush;
21+
f1.wait();
22+
f2.wait();
23+
f3.wait();
24+
std::cout << "Done!\nResults are: "
25+
<< f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
26+
t.join();
27+
}

0 commit comments

Comments
 (0)