- async原型:
template<class Fn, class... Args>
future<typename result_of<Fn(Args...)>::type> async(launch policy, Fn&& fn, Args&&...args);
- 线程创建策略:std::launch::async 实时创建线程====================std::launch::deferred 延迟创建线程,直到调用futrue的get,wait或wait_for才创建;
- 可调用线程执行函数:普通函数,成员函数,lambda表达式等(对比以前的静态函数,不多说)
void CAsync::CreateThread()
{
m_thread = std::async(std::launch::async, &CAsync::ThreadRun, this);//不带参数
auto iResult = m_thread.get();
printf("\niResut:%d \n", iResult);
auto thread = std::async(std::launch::async, &CAsync::Func, this, 4, 5);//带两个参数
thread.wait();
auto thread2 = std::async(std::launch::async, [](){ printf("thread2 create\n"); });//lambda表达式
thread2.get();
}
int CAsync::ThreadRun()
{
while (m_iData < 100)
{
m_iData++;
printf("%d ", m_iData);
}
return m_iData;
}
int CAsync::Func(int iData, int iTemp)
{
printf("iData:%d \n", iData);
return 0;
}
- 替代std::thread()进行异步操作:
m_thread = std::async(std::launch::async, [this]()
{
this->Run();
});
//m_thread.get();//程序运行到这里是阻塞的,线程函数内部执行完毕才开始返回
- async最大的特点就是能返回线程执行结果,那么futrue的get在哪使用呢?====现在图片处理算法算是比较常见,有时根据需求需要的算法时长较长,可以先创建线程,让线程函数运行起来,然后在需要的地方get();
- 线程函数在sleep过程中执行完毕,在thread.get()时能够马上返回执行结果,原本需要耗时执行的线程函数早已执行完毕,大大提高执行效率;
//单独执行大概需要1-2秒,懒得做测试
int CTest1::Func()
{
int iData = 0;
while (iData < 10000)
{
iData++;
}
printf("thread running\n");
return iData;
}
...
std::future<int> thread = std::async(std::launch::async, &CTest1::Func, &objTest1);//
std::this_thread::sleep_for(std::chrono::seconds(5));
printf("wait end\n");
auto data = thread.get();
printf("data:%d \n", data);z
- 调用实例:
#pragma once
#include <future>
class CBase
{
private:
void Init();
void Uninit();
virtual int Run();
public:
CBase();
virtual ~CBase();
protected:
int m_iData;
std::future<void> m_thread;
};
class CTest1 : public CBase
{
private:
virtual int Run() override;
public:
CTest1() {};
virtual ~CTest1() {};
};
class CTest2 : public CBase
{
private:
virtual int Run() override;
public:
CTest2() {};
virtual ~CTest2() {};
};
#include "stdafx.h"
#include "MutexTest.h"
#include <chrono>
//==============================================================
CBase::CBase() :m_iData(0)
{
Init();
}
CBase::~CBase()
{
Uninit();
}
void CBase::Init()
{
m_thread = std::async(std::launch::async, [this]()
{
this->Run();
});
//m_thread.get();//程序运行到这里是阻塞的,线程函数内部执行完毕才开始返回
}
void CBase::Uninit()
{
m_thread.wait();
}
int CBase::Run()
{
return 0;
}
//==============================================================
std::mutex g_mutex;
int CTest1::Run()
{
g_mutex.lock();
while (m_iData < 10)
{
printf("thread1:%d \n", m_iData++);
}
g_mutex.unlock();
return 0;
}
//==============================================================
int CTest2::Run()
{
g_mutex.lock();
while (m_iData < 10)
{
printf("thread2:%d \n", m_iData++);
}
g_mutex.unlock();
return 0;
}
#include "stdafx.h"
#include "MutexTest.h"
int _tmain(int argc, _TCHAR* argv[])
{
CTest1 objTest1;
CTest2 objTest2;
std::this_thread::sleep_for(std::chrono::seconds(1));
return 0;
}
- 执行结果: