用另一个超时线程杀死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();
}
答
您可以使用睡眠:
#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();
}
这具有便携的益处很小。
请注意在升压短耳的deadline_timer
类的了。
它看起来像你试图等待你的工作线程条件。如果是这样,您也可以等待截止日期为condition_variable
(cv.wait_until
或超时:cv.wait_for
)。
答
只是检查的时间在工作线程,你将不再需要一个单独的超时螺纹:
void WorkerThread()
{
DWORD nStartTime = GetTickCount();
while(boost::this_thread::interruption_requested() == false && GetTickCount() - nStartTime < 15000)
{
printf(".");
}
}
顺便说一句,请注意15000
,因为GetTickCount的()单位是毫秒
为什么你“破坏”代码,以便它不能编译?它离自我很近,但是你移除了类,错误地输入了'MyClass bTimeout',绑定了不存在的这些指针等等。在这种情况下,最好保留这个类,因为我只需要按顺序重新创建它编译... – sehe
另外,它似乎刚刚在超时线程上删除了'join()',请注意,现在这是无效的;所有的线程必须在应用程序终止之前连接或分离 – sehe
lol在编辑:/它仍然说'MyClass btimeout;'你仍然在主要绑定'this' ... _Never mind_。现在看到我对SSCCE的回答(和评论) – sehe