#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;
}
C++ async
于 2022-03-04 10:32:44 首次发布