为什么线程有不稳定的行为

Why thread has an unstable behaviour?

本文关键字:不稳定 线程 为什么      更新时间:2023-10-16

我有一个线程内部的时间,但程序只在某些情况下工作。我在c++编程,Boost 1.59和Visual studio 2012。下面的代码是:

while(condition){
      boost::thread t(GeneticAlgorithm);
          if(!t.timed_join(boost::posix_time::seconds(10))){
             //always entry here, because geneticAlgoritm is infinity 
             TerminateThread(t.native_handle(), 0);
             more calculus..
          }
}

我希望在10秒后停止线程并在返回"while"时创建另一个线程。我第一次运行线程工作,此后有时工作,有时不。任何想法?

无中断点,无中断。这里的中断不是软中断或硬件中断,而是协作中断。

您需要添加一个中断点,以便可以激活协作中断。

一个正在运行的线程可以通过调用interrupt()成员来中断对应boost::thread对象的函数。当被中断的线程接下来执行指定的中断之一点(或者如果当前在执行一个时被阻塞)中断被启用,那么boost::thread_interrupted异常将在被中断的线程中抛出。如果没有抓住,这将导致被中断线程的执行要终止。和任何否则,堆栈将被展开,析构函数为自动保存时长的对象将被执行。

你可以这样添加一个中断点。

bool GeneticAlgorithm() {
    ... some code
    // this point must be passed at least once every 10 sec.
    boost::this_thread::interruption_point(); 
    ... more code
}