我是靠谱客的博主 魔幻咖啡,这篇文章主要介绍C++11的std::async 和std::future,现在分享给大家,希望可以做个参考。

std::future

  std::future是一个非常有用也很有意思的东西,简单说std::future提供了一种访问异步操作结果的机制。从字面意思来理解,它表示未来,我觉得这个名字非常贴切,因为一个异步操作我们是不可能马上就获取操作结果的,只能在未来某个时候获取,但是我们可以以同步等待的方式来获取结果,可以通过查询future的状态(future_status)来获取异步操作的结果。future_status有三种状态:

  • deferred:异步操作还没开始
  • ready:异步操作已经完成
  • timeout:异步操作超时

获取future结果有三种方式:get、wait、wait_for,其中

  • get:等待异步操作结束并返回结果,
  • wait:只是等待异步操作完成,没有返回值,
  • wait_for:是超时等待返回结果。 

std::async

std::async的原型async(std::launch::async | std::launch::deferred, f, args...),第一个参数是线程的创建策略,有两种策略,默认的策略是立即创建线程:

  • std::launch::async:在调用async就开始创建线程。
  • std::launch::deferred:延迟加载方式创建线程。调用async时不创建线程,直到调用了future的get或者wait时才创建线程。

第二个参数是线程函数,第三个参数是线程函数的参数。

复制代码
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
43
44
45
#include<iostream> #include<thread> #include<string> #include<vector> #include<list> #include<mutex> #include<future> using namespace std; int mythread() //线程入口函数 { cout << "mythread start" << "threadid= " << std::this_thread::get_id() << endl; //打印线程id std::chrono::milliseconds dura(5000); //定一个5秒的时间 std::this_thread::sleep_for(dura); //休息一定时常 cout << "mythread end" << "threadid= " << std::this_thread::get_id() << endl; return 5; } int main() { cout << "main" << "threadid= " << std::this_thread::get_id() << endl; std::future<int> result = std::async(std::launch::async, mythread);//std::launch::deferred时进入std::future_status::deferred cout << "continue....." << endl; //枚举类型 std::future_status status = result.wait_for(std::chrono::seconds(10));//等待10秒是ready状态,1秒是timeout if (status == std::future_status::deferred) { //线程被延迟执行了,系统资源紧张 //cout << result.get() << endl; //此时采取调用mythread() //result.wait(); } else if (status == std::future_status::timeout)// { //超时:表示线程还没执行完;我想等待你1秒,希望你返回,你没有返回,那么 status = timeout //线程还没执行完 cout << "超时:表示线程还没执行完!" << endl; } else if (status == std::future_status::ready) { //表示线程成功返回 cout << "线程成功执行完毕,返回!" << endl; cout << result.get() << endl; } cout << "I love China!" << endl; return 0; }

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
void MyTest::testCls() { MyCls mydata; //async(类成员函数, 类对象, 参数1, 参数2,...,返回结果) std::future<bool> res = std::async(&MyCls::test, &mydata, hoImg, startPos, &rtnResult); res.wait(); m_cbk(&rtnResult); } void MyCls::test(Img hoImg, double startPos, int* rtnResult) { ...... }


 

最后

以上就是魔幻咖啡最近收集整理的关于C++11的std::async 和std::future的全部内容,更多相关C++11的std::async内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(83)

评论列表共有 0 条评论

立即
投稿
返回
顶部