小编aro*_*ola的帖子

主线程等待 std::async 完成

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

我得到输出:

Hello
Thread id is:22832
Entry
Thread id is:13156
Exit
After call
Run Code Online (Sandbox Code Playgroud)

c++ multithreading asynchronous stdasync

6
推荐指数
2
解决办法
4259
查看次数

标签 统计

asynchronous ×1

c++ ×1

multithreading ×1

stdasync ×1