c++多线程之async(),future

std::async()、std::future创建后台任务并返回值。希望线程返回一个结果。
std::async()是个函数模板,用来启动一个异步任务,启动这个异步任务之后,它返回一个std::future对象,这个std::future包含线程入口函数返回的结果(线程返回的结果),我们可以调用future的成员函数get()来获取。

int test(int x)
{
	cout << "Child threadID:" << std::this_thread::get_id() << endl;
	
	cout << "x:" <<x<< endl;
	this_thread::sleep_for(std::chrono::seconds(5));
	return x + 100;
}

void main()
{
	
	cout << "main threadID:" << std::this_thread::get_id() << endl;
	//创建一个线程,并开始运行,并不会卡在这里。
	std::future<int> fut = std::async(test, 11);
	Sleep(1000);
	for (int i = 0; i < 5;i++)
	{
		cout << "我在处理耗时任务" << i << endl;
		Sleep(1000);
	}

	int nRes = fut.get();
	cout << "nRes:" << nRes << endl;
	
	system("pause");
}

结果:
在这里插入图片描述
注意:如果std::async(…),开启的线程,如果调用get(),线程内部没有执行完,会阻塞在get()所在的地方;如果不使用get(),主线程退出的时候也会等待该子线程执行完毕才会退出,如果对于 int main() {…,return 0;},会卡在return 0;语句。

当然也可以使用类的成员函数,代码如下:

class A
{
public:
	int test(int x)
	{
		cout << "Child threadID:" << std::this_thread::get_id() << endl;

		cout << "x:" << x << endl;
		this_thread::sleep_for(std::chrono::seconds(5));
		return x + 100;
	}
};


void main()
{
	
	A a;
	cout << "main threadID:" << std::this_thread::get_id() << endl;
	std::future<int> fut = async(&A::test,&a, 11);
	

	int nRes = fut.get();
	cout << "nRes:" << nRes << endl;
	
	system("pause");
}

结果:
在这里插入图片描述
在这里插入图片描述
从结果的线程id可以看出,并没有创建新的线程,子线程ID
和主线程是一样的。这个问题很奇怪,我也不知道原因,如果有谁知道,请告我一声。
那如何让其开启一个线程呢?使用launch::async
部分代码如下:

void main()
{
	
	A a;
	cout << "main threadID:" << std::this_thread::get_id() << endl;
	std::future<int> fut = async(std::launch::async,&A::test,&a, 11);
	

	int nRes = fut.get();
	cout << "nRes:" << nRes << endl;
	
	system("pause");
}

结果:
在这里插入图片描述
所以我建议第一个参数还是使用std::launch::async

那如何让线程等待呢?使用std::launch::deferred
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
从结果可以看出,即使在主线程中调用get前等待了5秒,也会卡在get的地方,等待子线程执行完毕。就我个人而言,使用性并不大。
注意:如果使用了std::launch::deferred,如果没有使用get,或者wait,就不会被执行,相当于async(std::launch::deferred,&A::test,&a, 11);白写了!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发如雪-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值