What’s the best way to delete boost::thread object right after its work is complete?
我用
1 2 3 4 5 6 | void do_work() { // perform some i/o work } boost::thread *thread = new boost::thread(&do_work); |
我想,完成工作后有必要删除
来自
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.
编辑:如果只需要启动线程而从不调用
1 2 | // Launch thread. boost::thread(&do_work); |
但是,即使您认为确定在
您可以使用
1 2 | boost::thread t(&do_work); t.detach(); |
线程分离后,它不再归
我建议您使用boost :: shared_ptr,这样您在删除线程对象时就不会担心。
1 | boost::shared_ptr<boost::thread> thread(new boost::thread(&do_work)); |
您应该看一下线程中断。
这篇文章也很好。
http://www.boost.org/doc/libs/1_38_0/doc/html/thread/thread_management.html