#include <iostream>
#include <future>
#include <thread>
int main()
{
// 使用 packaged_task
std::packaged_task<int()> task([]() {
std::cout << "packaged_task started" << std::endl;
return 7; }); // wrap the function
std::future<int> f1 = task.get_future(); // get a future
std::thread(std::move(task)).detach(); // launch on a thread
// 使用 async()
std::future<int> f2 = std::async(std::launch::deferred, []() {
std::cout << "Async task started" << std::endl;
return 8; });
// 使用 promise
std::promise<int> p;
std::future<int> f3 = p.get_future();
std::thread([&p] { p.set_value_at_thread_exit(9); }).detach();
f1.wait();
f2.wait();
f3.wait();
std::cout << "Done!\nResults are: "
<< f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
}
c++11,future使用代码片段
最新推荐文章于 2024-06-02 14:55:46 发布