在完成工作后立即删除 boost::thread 对象的最佳方法是什么?

2021-12-24 00:00:00 multithreading c++ boost boost-thread

我用一个 new 操作符创建了 boost::thread 对象并继续而不等待这个线程完成它的工作:

I create boost::thread object with a new operator and continue without waiting this thread to finish its work:

void do_work()
{
    // perform some i/o work
}

boost::thread *thread = new boost::thread(&do_work);

我想,当工作完成时,有必要删除thread.不显式等待线程终止的最佳方法是什么?

I guess, it’s necessary to delete thread when the work is done. What’s the best way to this without explicitly waiting for thread termination?

推荐答案

boost::thread 对象的生命周期与本机线程的生命周期无关.boost::thread 对象可以随时超出范围.

The boost::thread object's lifetime and the native thread's lifetime are unrelated. The boost::thread object can go out of scope at any time.

来自 boost::thread 类 文档

正如文件的生命周期可能与代表文件的 iostream 对象的生命周期不同,执行线程的生命周期可能与代表执行线程的线程对象的生命周期不同.特别是,在调用 join() 之后,即使线程对象继续存在直到其正常生命周期结束,执行线程也将不再存在.反过来也是可能的;如果一个线程对象在没有首先调用 join() 的情况下被销毁,则该线程将继续执行,直到其初始函数完成.

Just as the lifetime of a file may be different from the lifetime of an iostream object which represents the file, the lifetime of a thread of execution may be different from the thread object which represents the thread of execution. In particular, after a call to join(), the thread of execution will no longer exist even though the thread object continues to exist until the end of its normal lifetime. The converse is also possible; if a thread object is destroyed without join() having first been called, the thread of execution continues until its initial function completes.

编辑:如果你只需要启动一个线程并且从不调用join,你可以使用线程的构造函数作为一个函数:

Edit: If you just need to start a thread and never invoke join, you can use the thread's constructor as a function:

    // Launch thread.
boost::thread(&do_work); 

然而,我不建议你这样做,即使你认为你确定线程会在 main() 之前完成.

However, I don't suggest you do that, even if you think you're sure the thread will complete before main() does.

相关文章