从 void 方法启动线程
Starting a thread from a void method
使用 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();
}
相关文章:
- 使用 std::string () const 函数启动线程或未来
- 如何创建线程序列以按照启动顺序执行任务?
- 启动类函数作为失去引用的线程
- 重新启动后,线程无法在 while 循环中再次运行
- 如何在C++上启动异步线程
- 计时器是否从另一个线程启动?
- 如何在 MFC 应用程序中启动 ZeroMQ 线程?
- C++ POCO - 如何在不使用 run() 方法的情况下启动线程池上的线程?
- 为什么 pthread_create() 返回 0 但线程从未启动
- 为什么 cuda-gdb 会启动多个线程?
- 对于每个线程,random_device是否以不同的状态启动?
- 线程启动延迟 - 通知所有未唤醒所有线程
- 等待多个线程启动,start() 未捕获
- Qt多线程启动线程错误
- 用信号通知线程启动特定的函数
- C++简单的线程启动问题
- - C++ - 使用计时器线程启动异常,精度毫秒
- 传递字符串作为线程启动例程参数:c++
- 错误:无法从另一个线程启动计时器.使用未声明计时器的QFuture
- QT线程:获取QObject::startTimer:计时器无法从另一个线程启动警告