本文介绍了主线程等待std :: async完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用std::async创建一个线程,我希望这个新线程应该单独执行,而主线程不应该等待它.但是在这里,当我调用std :: async时,会创建一个新线程,但是主线程正在等待fun()的完成.我希望主线程能够并行执行而不必等待fun()完成.我该怎么办?

I am using std::async to create a thread, I want this new thread should execute separately and main thread should not wait for it. But here when I call std::async, a new thread is created but main thread is waiting for completion of fun(). I want main thread to execute parallely without waiting for fun() to complete. How should I do that?

#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

推荐答案

std::async返回并使用std::launch::async策略启动的std::future对象,阻止销毁,直到启动的任务完成.

A std::future object returned by std::async and launched with std::launch::async policy, blocks on destruction until the task that was launched has completed.

由于您没有将返回的std::future存储在变量中,因此在语句末尾使用std::async将其销毁,因此,main在任务完成之前无法继续.

Since you do not store the returned std::future in a variable, it is destroyed at the end of the statement with std::async and as such, main cannot continue until the task is done.

如果存储std::future对象,则其生存期将延长至main的末尾,并且您将获得所需的行为.

If you store the std::future object, its lifetime will be extended to the end of main and you get the behavior you want.

int main()
{
    ...
    auto fut = std::async(std::launch::async, fun, nullptr);
    ...
}

这篇关于主线程等待std :: async完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:49
查看更多