stl 的std::async阻塞不能异步原因分析

本文分析了在使用C++ STL的std::async时出现的阻塞现象,通过实例展示了问题所在,并解释了原因:std::async创建的future临时对象在当前语句作用域结束即被销毁,导致阻塞。解决方法是返回future对象以延长其生命周期。

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

1、看个例子:

#include <stdarg.h>
#include <thread>
#include <future>
#include <iostream>
#include <unistd.h>
using namespace std;
 
void test()
{
	
    for (int i = 0; i < 5; ++i)
	{
		sleep(1);
		cout << i << endl;
	}		
	
	//f.wait();
	cout<< "finished test" << endl;
}
int main()
{
	std::async(std::launch::async,test);
	while (1){
		cout << "main thread" << endl;
		sleep(1);
	}
	cout << "end test" << endl;
	return 0;
}

运行结果:

0
1
2
3
4
finished test
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread

2、修改代码如下: 

#include <stdarg.h>
#include <thread>
#include <future>
#include <iostream>
#include <unistd.h>
using namespace std;
 
void test()
{
     
        
	for (int i = 0; i < 5; ++i)
	{
			sleep(1);
			cout << i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值