Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a software watchdog timer thread in C++ using Boost Signals2 and Threads?

I am running function Foo from somebody else's library in a single-threaded application currently. Most of the time, I make a call to Foo and it's really quick, some times, I make a call to Foo and it takes forever. I am not a patient man, if Foo is going to take forever, I want to stop execution of Foo and not call it with those arguments.

What is the best way to call Foo in a controlled manner (my current environment is POSIX/C++) such that I can stop execution after a certain number of seconds. I feel like the right thing to do here is to create a second thread to call Foo, while in my main thread I create a timer function that will eventually signal the second thread if it runs out of time.

Is there another, more apt model (and solution)? If not, would Boost's Signals2 library and Threads do the trick?

like image 778
Aron Ahmadia Avatar asked Jun 18 '09 22:06

Aron Ahmadia


1 Answers

You can call Foo on a second thread with a timeout. For example:

#include <boost/date_time.hpp> 
#include <boost/thread/thread.hpp>

boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(500);
boost::thread thrd(&Foo);

if (thrd.timed_join(timeout))
{
  //finished
}
else
{
  //Not finished;
}
like image 10
Dani van der Meer Avatar answered Nov 12 '22 15:11

Dani van der Meer