我std::async
用来创建一个线程,我希望这个新线程应该单独执行,主线程不应该等待它。但是在这里,当我调用 std::async 时,会创建一个新线程,但主线程正在等待fun()
. 我希望主线程在不等待fun()
完成的情况下并行执行。我该怎么做?
#include <iostream>
#include <windows.h>
#include <future>
using namespace std;
void printid()
{
cout << "Thread id is:" << this_thread::get_id() << endl;
}
void fun(void *obj)
{
cout<<"Entry"<<endl;
printid();
Sleep(10000);
cout<<"Exit"<<endl;
}
int main()
{
cout<<"Hello"<<endl;
printid();
std::async(std::launch::async, fun, nullptr);
cout << "After call" << endl;
}
我得到输出:
Hello
Thread id is:22832
Entry
Thread id is:13156
Exit
After call