简体   繁体   English

我如何知道是否完成了增强螺纹?

[英]How do I know if a boost thread is done?

I am using boost::thread to process messages in a queue. 我使用boost :: thread来处理队列中的消息。 When a first message comes I start a message processing thread. 当第一条消息出现时,我启动了一个消息处理线程。 When a second message comes I check if the message processing thread is done. 当第二条消息出现时,我检查消息处理线程是否完成。

if it is done I start a new one if it is not done I don nothing. 如果它完成了我开始一个新的如果它没有完成我什么都不做。

How do I know if the thread is done ? 我怎么知道线程是否完成? I tried with joinable() but it is not working, as when the thread is done, it is still joinable. 我尝试使用joinable()但它不起作用,因为当线程完成时,它仍然可以连接。

I also tried to interrupt the process at once, and add an interruption point at the end of my thread, but it did not work. 我也试图立即中断进程,并在我的线程末尾添加一个中断点,但它没有用。

Thanks 谢谢

EDIT : 编辑:

I would like to have my thread sleep for an undetermined time, and wake up when a signal is triggered. 我想让我的线程在不确定的时间内休眠,并在触发信号时唤醒。

The mean to do it is boost::condition_variable 这样做的意思是boost :: condition_variable

As far as I know you should use the join() method to wait the end of a thread execution. 据我所知,你应该使用join()方法等待线程执行的结束。 You can use it with a timeout with timed_join(). 你可以使用timed_join()超时使用它。

You can interrupt threads with interrupt(). 您可以使用interrupt()中断线程。 In this case, inside the thread an exception will occur if the execution reaches an interruption point ( a boost::this_thread::sleep() or boost::this_thread::interruption_point() ). 在这种情况下,如果执行到达中断点(boost :: this_thread :: sleep()或boost :: this_thread :: interruption_point()),则在线程内部将发生异常。 You catch the exception inside the thread and you can then close it. 您在线程内捕获异常,然后可以关闭它。

Spawning a new thread for each incoming message is very inefficient. 为每个传入消息生成一个新线程是非常低效的。 You should check out the Thread pool pattern . 你应该看看线程池模式

EDIT: 编辑:

Sorry, jules, I misread your question. 对不起,jules,我误解了你的问题。 I recommend you take a look at the producer-consumer pattern. 我建议你看一下生产者 - 消费者模式。 Check out this article on how to roll your own blocking queue using boost condition variables. 查看本文 ,了解如何使用boost条件变量滚动自己的阻塞队列。 Intel's Thread Building Blocks also has a blocking queue implementation. 英特尔的线程构建模块也有阻塞队列实现。

Check out this SO question about existing lock-free queue implementations. 查看有关现有无锁队列实现的SO 问题

Hope this helps. 希望这可以帮助。

Have you tried checking get_id() with boost::this_thread::get_id(). 您是否尝试使用boost :: this_thread :: get_id()检查get_id()。 If they match the thread does not exist. 如果匹配则线程不存在。 But that will only happen if you have exited the thread. 但只有退出线程才会发生这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM