从 void 方法启动线程

Starting a thread from a void method

本文关键字:线程 启动 方法 void      更新时间:2023-10-16

使用 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;
}

startThread()完成时,t 会尝试删除,但会失败。我该怎么做?

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

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

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

std::thread startThread()
{
    return std::thread(longFunc);
}

无论如何,您可以考虑通过std::async()启动线程并返回future对象。这将是异常安全的,因为在启动的线程中抛出的异常将被 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();
}