用另一个超时线程杀死Boost线程

问题描述:

我想在经过一段时间后结束线程WorkerThread。 我正在考虑为此使用第二个线程TimeoutThread,它在15秒后更改一个标记,以便另一个线程停止。 有没有一种更优雅的方式来提升呢?用另一个超时线程杀死Boost线程

#include <boost/thread.hpp> 

struct MyClass 
{ 
    boost::thread timeoutThread; 
    boost::thread workerThread; 
    bool btimeout = true; 

    void run() 
    { 
    timeoutThread = boost::thread(boost::bind(&MyClass::TimeoutThread, this)); 
     workerThread = boost::thread(boost::bind(&MyClass::WorkerThread, this)); 
    workerThread.join(); 
    TimeoutThread.join(); 
    } 


    void WorkerThread() { 

     while(boost::this_thread::interruption_requested() == false && btimeout) 
     { 
      printf("."); 

     } 
    } 

    void TimeoutThread() 
    { 
     boost::this_thread::disable_interruption oDisableInterruption; 
     DWORD nStartTime = GetTickCount(); 

     while(boost::this_thread::interruption_requested() == false) 
     { 
      if(GetTickCount() - nStartTime > 15) 
      { 
       m_bTimeout = false; 
       break; 
      } 
     } 

    } 
}; 

int main() 
{ 
    MyClass x; 
    x.run(); 
} 
+1

为什么你“破坏”代码,以便它不能编译?它离自我很近,但是你移除了类,错误地输入了'MyClass bTimeout',绑定了不存在的这些指针等等。在这种情况下,最好保留这个类,因为我只需要按顺序重新创建它编译... – sehe

+0

另外,它似乎刚刚在超时线程上删除了'join()',请注意,现在这是无效的;所有的线程必须在应用程序终止之前连接或分离 – sehe

+0

lol在编辑:/它仍然说'MyClass btimeout;'你仍然在主要绑定'this' ... _Never mind_。现在看到我对SSCCE的回答(和评论) – sehe

您可以使用睡眠:

#include <boost/thread.hpp> 

struct MyClass 
{ 
    boost::thread timeoutThread; 
    boost::thread workerThread; 

    void TimeoutThread() { 
     boost::this_thread::sleep_for(boost::chrono::milliseconds(15)); 
     workerThread.interrupt(); 
    } 

    void WorkerThread() { 
     while(!boost::this_thread::interruption_requested()) 
     { 
      //Do stuff 
     } 
    } 

    void run() 
    { 
     timeoutThread = boost::thread(boost::bind(&MyClass::TimeoutThread, this)); 
     workerThread = boost::thread(boost::bind(&MyClass::WorkerThread, this)); 
     workerThread.join(); 
     timeoutThread.join(); 
    } 
}; 

int main() 
{ 
    MyClass x; 
    x.run(); 
} 

这具有便携的益处很小。

看到它live on Coliru

请注意在升压短耳的deadline_timer类的了。

它看起来像你试图等待你的工作线程条件。如果是这样,您也可以等待截止日期为condition_variablecv.wait_until或超时:cv.wait_for)。

+0

谢谢!这可能会起作用,但我使用boost 1.49.0,这似乎只适用于我认为的中继版本。 – tzippy

+0

我使用1_55但AFAIR它已经在早期版本 – sehe

+0

@tzippy此外,这是相当于std C++ 11:** [std = C++ 11 only](http://coliru.stacked-crooked.com/a/ec18be849ff68565)**和等效** [仅限于升压](http://coliru.stacked-crooked.com/a/28a250f23e34852a)**。这不应该要求任何“新”或“奇特”。 – sehe

只是检查的时间在工作线程,你将不再需要一个单独的超时螺纹:

void WorkerThread() 
{ 
    DWORD nStartTime = GetTickCount(); 
    while(boost::this_thread::interruption_requested() == false && GetTickCount() - nStartTime < 15000) 
    { 
     printf("."); 

    } 
} 

顺便说一句,请注意15000,因为GetTickCount的()单位是毫秒

+0

为什么我们会假设他没有_want_ **毫秒**? – sehe

+1

@sehe:“在15 **秒**之后改变旗帜”,当然这也可能是一个错误:) –

+0

Ahaha。我错过了 :) – sehe