项目:异步

场合

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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值