什么是删除线程对象权利的工作完成后,最好的方法是什么? [英] What’s the best way to delete boost::thread object right after its work is complete?

查看:128
本文介绍了什么是删除线程对象权利的工作完成后,最好的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个运营商的boost ::线程对象,并继续无需等待这个线程完成其工作

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);

我想,有必要删除线程当工作就完成了。什么是最好的办法没有明确等待线程终止?

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 ::线程对象的生命周期和本地线程的生命周期无关。在的boost ::线程对象可以在任何时候走出去的范围。

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 ::线程类<一href=\"http://www.pdc.kth.se/training/Talks/C++/boost/libs/thread/doc/thread.html\">documentation

正如文件的寿命可能会从中重新presents iostream对象的生命周期文件,执行的线程的生命周期可能会从中重新presents的线程对象不同不同执行线程。特别是经过一个号召,加入(),执行的线程将不复存在,即使线程对象将继续存在,直到它的正常寿命的结束。反过来也是可能的;如果一个线程对象被销毁无连接()最早被调用,执行线程继续进行,直到其最初的功能完成。

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.

修改:如果你只需要启动一个线程,从来没有调用加入,您可以使用线程的构造函数的函数:

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()一样。

这篇关于什么是删除线程对象权利的工作完成后,最好的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆