同步并发操作

文章详细介绍了C++中用于异步编程的关键组件,包括std::future,它允许从不同线程的安全获取值;std::async函数,可以异步调用并返回future;std::promise,用于存储异步操作的结果供future获取;以及std::packaged_task,封装可调用对象并自动将结果传递给future。这些工具提供了多线程间的同步点,确保了数据访问的安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、条件变量

2、std::future

https://cplusplus.com/reference/future/future/

A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads.
“Valid” futures are future objects associated to a shared state, and are constructed by calling one of the following functions:
1. async
2. promise::get_future
3. packaged_task::get_future

future objects are only useful when they are valid.
Default-constructed future objects are not valid (unless move-assigned
a valid future).
Calling future::get on a valid future blocks the thread until the provider makes the shared state ready (either by setting a value or an exception to it). This way, two threads can be synchronized by one waiting for the other to set a value.

The lifetime of the shared state lasts at least until the last object with which it is associated releases it or is destroyed. Therefore, if associated to a future, the shared state can survive the object from which it was obtained in the first place (if any).

3. std::async

unspecified policy (1)	
template <class Fn, class... Args>  future<typename result_of<Fn(Args...)>::type>    async (Fn&& fn, Args&&... args);
specific policy (2)	
template <class Fn, class... Args>  future<typename result_of<Fn(Args...)>::type>    async (launch policy, Fn&&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值