std::shared_future是C++11的标准库类,其与std::future的不同是允许多个线程使用,多个线程可以同步共享,同时其又不会阻塞等待异步任务的完成。std::shared_future同样也提供get()方法用于获取异步执行的结果。
#include <iostream> #include <thread> #include <future> void promise_string(std::promise<std::string> &pr) { for (int i = 0; i < 100; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::cout << "sleep" << std::endl; } std::string str = "the current function name is: "; str.append(__FUNCTION__); pr.set_value(str); } int main() { std::promise<std::string> pr; std::future<std::string> fu(pr.get_future()); std::shared_future<std::string> sfu(fu.share()); std::thread t1([&sfu]() { std::string str = sfu.get(); std::cout << "thread1 function is: " << str.c_str() << std::endl; }); std::thread t2([&sfu]() { std::string str = sfu.get(); std::cout << "thread2 function is: " << str.c_str() << std::endl; }); std::async(std::launch::async, [&pr]() { promise_string(pr); }); //std::async(std::launch::async, promise_string,ref(pr)); t1.join(); t2.join(); system("pause"); }
std::promise和std::future用于创建异步任务和获取其结果,通过fu.share()函数创建一个std::share_future对象,用于共享异步任务结果。创建两个线程并发获取共享结果,线程调用sfu.get()获取异步执行结果。
标签:库类,std,sfu,异步,get,C++,future,shared From: https://www.cnblogs.com/missyou0813/p/17859416.html