如何中断等待C ++ 0x线程? [英] How to interrupt a waiting C++0x thread?

查看:184
本文介绍了如何中断等待C ++ 0x线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑在我的应用程序中使用C ++ 0x线程,而不是Boost线程。但是,我不知道如何重新实现我对标准C ++ 0x线程,因为他们似乎没有 interrupt()方法。

I'm considering to use C++0x threads in my application instead of Boost threads. However, I'm not sure how to reimplement what I have with standard C++0x threads since they don't seem to have an interrupt() method.

我当前的设置是:


  • 一个管理工作的主线程;

  • a master thread that manages work;
  • several worker threads that carry out master's commands.

工作者调用 wait() 至少两个不同的条件变量。主人有一个超时状态:在这种情况下,它告诉所有工人停止和给出任何他们得到的结果。使用Boost线程主程序只在线程组上使用 interrupt_all(),这会导致工作线程停止等待。如果他们没有在等待,master也会设置一个 bool 标志,工人会定期检查。

Workers call wait() on at least two different condition variables. Master has a "timed out" state: in this case it tells all workers to stop and give whatever result they got by then. With Boost threads master just uses interrupt_all() on a thread group, which causes workers to stop waiting. In case they are not waiting at the moment, master also sets a bool flag which workers check periodically.

,在C ++ 0x std :: thread 我没有看到任何替换 interrupt()。我错过什么吗?

However, in C++0x std::thread I don't see any replacement for interrupt(). Do I miss something? If not, how can I implement the above scheme so that workers cannot just sleep forever?

推荐答案

不幸的是,我没有看到另一个

Unfortunately I don't see another way than polling, instead of using wait use a timed wait and a variable to state the interruption has been done.

void th(Interruptor& interruptor) {
  try {

    ...

    while (cnd1.timed_wait(d)==false) {
      interruptor.check_interruption_point();
    }
    ...
  } catch (interrupted_exception &) {}
}

Interruptor类将维护一个布尔变量,使用互斥锁保护,或者使用原子操作,如果你有它们,并且两个函数中断和check_interruption_point,如果布尔值为真则抛出一个interrupted_exception。 Mater线程将创建一个Interruptor变量,将在创建时给予相关线程。主机具有立即中断所有依赖于该中断器的线程的可能性。你当然可以为每个线程创建一个中断器,如果你想显式地中断一个线程一次。

The Interruptor class will maintain a boolean variable protected with a mutex or using atomic operations if you have them and two functions interrupt and check_interruption_point, which with throw a interrupted_exception if the boolean is true. The Mater thread will create an Interruptor variable that will be given to the concerned threads at creation time. The master has the the possibility to interrupt at once all the threads that depends on this interruptor. You can of course create an interruptor for each thread if you want to explicitly interrupt one thread at a time.

直到你定义的时间等待的持续时间,因此,你的线程能够在程序需要时立即作出反应。

Up to you to define the duration on the timed wait, so your threads are able to react as soon as your program require.

这篇关于如何中断等待C ++ 0x线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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