问题
I want to end a thread WorkerThread
after a certain amount of time has elapsed.
I was thinking to use a second thread TimeoutThread
for this, that changes a flag after 15 seconds so the other thread stops.
Is there a more elegant way in boost to do this?
#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:
You could use a sleep:
#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();
}
This has the minimal benefit of being portable.
See it live on Coliru
Please be aware of the deadline_timer
class in Boost Asio too.
And it looks like you're trying to await a condition in your worker thread. If so, you can also await a condition_variable
with a deadline (cv.wait_until
or with a timeout: cv.wait_for
).
回答2:
Just check time in worker thread and you won't need a separate timeout thread:
void WorkerThread()
{
DWORD nStartTime = GetTickCount();
while(boost::this_thread::interruption_requested() == false && GetTickCount() - nStartTime < 15000)
{
printf(".");
}
}
BTW, please note 15000
, because GetTickCount() units are milliseconds
来源:https://stackoverflow.com/questions/22763146/kill-boost-thread-with-another-timeout-thread