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

std::async std::future创建后台任务

std::async函数模板,用来启动一个异步任务返回一个std::future对象,future是个类模板

异步任务,自动创建一个线程并执行线程入口函数,返回的future对象里就含有入口函数返回的结果

头文件include<future>

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<thread> #include <iostream> #include<future> using namespace std; int mythread() { cout << "thread id = " << this_thread::get_id() << endl; chrono::milliseconds drue(2000); std::this_thread::sleep_for(drue); cout << "thread id = " << this_thread::get_id() << endl; return 5; } int main() { cout << "main id" << this_thread::get_id() << endl; future<int> result = async(mythread); cout << "countinue......" << endl; cout << result.get() << endl; cout << "i love china" << endl; return 0; }

 

可以看到,运行结果会先输出子线程ID,然后卡住两秒,再输出5,最后main结束。

因为result.get()函数调用时子线程还阻塞着的,result并没得到子线程函数返回的5,所以result.get()会持续等待直到返回。

future.get()只能调用一次

给async传递的第一个参数如果是std::launch::deferred。那么线程会等待直到get(),或者wait()函数调用才会创建。延迟创建线程

最后

以上就是勤恳可乐最近收集整理的关于C++ std::async std::future的全部内容,更多相关C++内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部