1 #include<iostream>
2 #include<future>
3 #include<thread>
4 #include<chrono>
5
6 int func(int arv)
7 {
8 std::this_thread::sleep_for(std::chrono::seconds(5)); //睡眠5秒
9 return arv &= 0xFF;
10 }
11
12 void testfuture()
13 {
14 //通过std::future获取异步操作线程函数的返回值, 这里用std::async创建异步的task
15 std::future<int> fu = std::async(func, 3);
16
17 //获取future结果有三种方式:
18
19 //1. fu.wait(); //等待线程结束,无返回值
20 //2. auto res = fu.get(); //等待线程结束并获取返回值
21
22 //3. 用wait_for查询future的状态, future的状态有三种
23 std::future_status status;
24 do
25 {
26 status = fu.wait_for(std::shrono::seconds(1));
27 if(status == std::future_status::deferred) //异步操作还没开始
28 std::cout << "deferred" << std::endl;
29 else if(status == std::future_status::timeout) //异步操作超时
30 std::cout << "timeout" << std::endl;
31 else if(status == std::future_status::ready) //异步操作已完成
32 std::cout << "ready" << std::endl;
33
34 }while(status != std::future_status::ready);
35 }
36
37 int main(int argc, char* argv[])
38 {
39 testfuture();
40 return 0;
41 }
c++11 std::future获取异步线程函数的返回值
最新推荐文章于 2025-04-12 12:56:17 发布