C++ async

#include "thread_pool.h"
#include <iostream>
#include <vector>
#include <thread>
#include <list>
#include <mutex>
using namespace std;

class A
{
public:
	int myth(int m)
	{

		cout << "myth start() " << "th_id:" << std::this_thread::get_id() << endl;
		std::chrono::milliseconds dura(5000);
		std::this_thread::sleep_for(dura);
		cout << "myth end() " << "th_id" << std::this_thread::get_id() << endl;
		return m;

	}
};



int main()
{
	//一:std::async,std::future创建后台任务返回值
	//a).std::launch::deferred延时调用,没有创建新线程,是在主线程中调用的线程入口函数
	  //如果wait()或wait()没调用,那么线程不好执行,实际上,线程根本没创建。
	//b).std::launch::async,在调用async函数的时候就开始创建线程
	    //async()函数默认的就是std::launch::async.
	A a; 
	int m_temp = 12;
	cout << "main()" << "th_id" << std::this_thread::get_id() << endl;
	//第二个参数使用对象引用,才能保证用的是同一个对象
	std::future<int>res = std::async(std::launch::async,&A::myth,&a,m_temp);
	
	std::cout << "continue..." << endl;
	int def;
	def = 0;
	cout << res.get() << endl;//只能调用一次
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值