从void方法启动一个线程

Tob*_*oby 3 c++ multithreading

使用C++,我想从void方法启动一个线程,然后在线程完成之前返回.例如:

#include <thread>
using namespace std;

void longFunc(){
  //stuff
}

void startThread(){
  thread t(longFunc);
}

int main(void){
  startThread();
  //lots of stuff here...
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

startThread()完成后,T试图删除,并失败.我怎样才能做到这一点?

And*_*owl 8

如果你真的想要一个即发即弃模式,你可以从线程中分离出来:

void startThread(){
    thread t(longFunc);
    t.detach();
}
Run Code Online (Sandbox Code Playgroud)

或者如果你需要加入线程(这通常是一个合理的东西),你可以简单地std::thread按值返回一个对象(线程包装器是可移动的):

std::thread startThread()
{
    return std::thread(longFunc);
}
Run Code Online (Sandbox Code Playgroud)

无论如何,您可以考虑启动线程std::async()并返回一个future对象.这将是异常安全的,因为在启动的线程中抛出的异常将被未来对象吞噬,并在您调用get()它时在主线程中再次抛出:

#include <thread>
#include <future>

void longFunc()
{
  //stuff
}

std::future<void> startThread()
{
    return std::async(std::launch::async, longFunc);
}

int main(void)
{
    auto f = startThread();
    //lots of stuff here...

    // For joining... (wrap in a try/catch block if you are interested
    //                 in catching possible exceptions)
    f.get();
}
Run Code Online (Sandbox Code Playgroud)