What’s the best way to delete boost::thread object right after its work is complete?(在完成工作后立即删除 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.
这篇关于在完成工作后立即删除 boost::thread 对象的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在完成工作后立即删除 boost::thread 对象的最佳方法是什么?
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01