范例一:
#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
void aa()
{
std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
while (1) {
}
}
void run()
{
//启动一个异步的线程,返回结果是一个函数模板,
auto it = std::async(aa);
}
int main()
{
//run();
//用{}限制下std::async函数模板的作用域,注意看打印结果,由于aa函数里面有一个while循环
//所以,在std::async还没有析构之前,只会打印出一个主线程ID,后续的不会打印,
{
auto it = std::async(aa);
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
}
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
return 0;
}
范例二:
#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
int run()
{
std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
return 3;
}
int main()
{
//启动一个异步线程
auto it = std::async(run);
std::cout << it.get() << std::endl; //获取函数返回结果
return 0;
}
范例三:
#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
int run()
{
std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
return 3;
}
int main()
{
//启动一个异步线程
auto it = std::async(run);
it.wait(); //等待线程返回
return 0;
}
范例四:
#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
int run()
{
std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
return 3;
}
int main()
{
//启动一个异步线程
auto it = std::async(std::launch::deferred,run);
std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
//如果没有调用wait成员函数或者get成员函数,则不会调用run函数,
//如果调用了这些成员函数,者会调用run函数,但是不会创建新的线程
it.wait(); //等待线程返回
return 0;
}
std::async的参数还有其它,大家可以自行尝试。