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

What’s the best way to delete boost::thread object right after its work is complete?

我用new运算符创建了boost::thread对象,并继续执行而无需等待该线程完成其工作:

1
2
3
4
5
6
void do_work()
{
    // perform some i/o work
}

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

我想,完成工作后有必要删除thread。无需显式等待线程终止的最佳方法是什么?


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

来自boost::thread类文档

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,则可以将线程的构造函数用作函数:

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

但是,即使您认为确定在main()之前完成线程,我也不建议您这样做。


您可以使用

1
2
boost::thread t(&do_work);
t.detach();

线程分离后,它不再归boost::thread对象所有;该对象可以被破坏,线程将继续运行。如果对象拥有一个正在运行的线程,则boost::thread析构函数也会调用detach(),因此让t被销毁将具有相同的结果。


我建议您使用boost :: shared_ptr,这样您在删除线程对象时就不会担心。

1
boost::shared_ptr<boost::threa> thread(new boost::thread(&do_work));


您应该看一下线程中断。

这篇文章也很好。

http://www.boost.org/doc/libs/1_38_0/doc/html/thread/thread_management.html