C++11异步操作(二)

1、async

        async是一个函数模板,用来启动一个异步任务,启动异步任务后,返回一个future对象。这个future对象里含有线程入口函数锁返回的结果(线程返回结果),可通过future对象的成员函数get()来获取。

 

2、future

(1)future:

       将来的意思,提供了一种访问异步操作结果的机制,此结果可能没马上拿到,可在线程执行完毕后拿到结果,该结果可使用future类中get()函数来获取。

(2)launch::deferred和launch::async

       launch::deferred:表示线程入口函数调用被延迟到future的wait()或者get()调用时才执行 若wait()或get()没调用,那么线程是不执行的,并且没创建新线程,是在主线程中调用线程入口函数。

       launch::async:在调用async函数时立刻开始创建线程async()函数默认使用launch::async,所以一般省略此参数。

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <future>

using namespace std;

class A
{
public:
	A() {}
	~A() {}

	int myThread(int tm)
	{
		cout << "tm = " << tm << endl;
		cout << "myThread() start, threadID = " << this_thread::get_id() << endl;
		chrono::microseconds dura(5000);	// 定义时长,5秒
		this_thread::sleep_for(dura);		// 休眠一定时长
		cout << "myThread() end, threadID = " << this_thread::get_id() << endl;
		return 5;
	}

};


int main()
{
	A a;
	int tm = 122;
	cout << "main ,threadID = " << this_thread::get_id() << endl;
	future<int> result = async(&a
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值