使用async创建一个新线程,返回一个future类型的对象,可以使用这种方法从线程中返回值。基本语法为:
std::future<线程函数返回值类型> res = std::async(标记, 线程入口函数);
标记常用的有std::launch::deferred和std::launch::async。
std::launch::async:意思是为当执行此行语句时线程被创建并开始执行,但是如果此线程没有被执行完,会被阻塞在res.get()或者res.wait(),直到执行完才被返回。
std::launch::deferred:不会创建新线程,当主线程执行到res.get()或者res.wait()之后会执行新线程里的内容并返回,效果类似与函数调用。
std::launch::async | std::launch::deferred:为系统默认缺省参数,含义为操作系统自行决定是否是async还是deferred(一般会创建新线程,但是如果系统资源紧张就会在当前线程执行)。
先看一个简单的例子:
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <future>
int mythread()
{
sleep(3);
std::cout << "another thread starts, thread id is " << std::this_thread::get_id() << '\n';
std::cout << "another thread ends\n";
return 10