场合
1. 耗时操作:CPU耗时运算/音视频解码/图片处理
2. 并发:异步加载图片/配置文件/文件读写
3. 本质:线程
sync
future async(launch policy, Function f, Args&&… args)
1. future:返回类型,future对象用于获取任务执行结果
2. std::launch::async:急速求值,立即启动一个线程,在线程中运行任务
3. std::launch::deferred:惰性求值,调用future.get()或future.wait()获取返回值时才在当前线程中运行(相当于同步)
4. 如果使用std::launch::async时任务运行很耗时,在future.get()获取返回值时线程还没运行完,此时调用线程会阻塞直到get到返回值
5. std::launch::any:即 any = async | deferred。可能创建新线程,也可能延迟调用,系统会根据当前的资源情况选择合适的方式
future async(Function f, Args&&…args)
当不含launch参数时,可能创建新线程,也可能延迟调用,系统会根据当前的资源情况选择合适的方式
实现
#include<futrue>
std::string str = "hello";
1. 函数
std::future<std::string> fun = std::async(callback, str);
fun.get();
2. 函数对象
class A {
public:
std::string operate(const string &str) {
return str;
}
}
A a;
auto obj = std::async(a, args);
obj.get();
3. 匿名函数
auto lam = std::async([](const string &str){return str;});
lam.get();
注意:当主线程调用get()时,如果子线程还没运行完,则主线程阻塞等待子线程
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
std::string callback(std::string str) {
std::cout << "sleep" << 5 << " seconds\n";
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::cout << str << std::endl;
return str;
}
int main() {
std::string str = "callback";
std::future<std::string> fun = std::async(std::launch::async, callback, str);
// std::future<std::string> fun = std::async(std::launch::deferred, callback, str);
std::cout << "get" << std::endl;
fun.get();
std::cout << "end" << std::endl;
}
// g++ -o exe main.cpp -std=c++11 -pthread && ./exe
2004

被折叠的 条评论
为什么被折叠?



