I have written a threaded timer that will start on command, and stop on command using the boost threads library. here’s the code:
/* copyright Benjamin Collins 2006
* please contact for licensing information */
#include
#include
#include
#include
#include
#include
typedef boost::recursive_mutex::scoped_lock rt_slock;
namespace
{
bool _start = false;
boost::recursive_mutex start_mutex;
boost::condition start_condition;
bool started()
{
return _start;
}
void start()
{
rt_slock lk(start_mutex);
_start = true;
}
void stop()
{
rt_slock lk(start_mutex);
_start = false;
}
}
class timer_func
{
public:
timer_func()
{
boost::xtime_get(&_time, boost::TIME_UTC);
}
void operator()()
{
while(true)
{
{
rt_slock lk(start_mutex);
start_condition.wait(lk);
}
while(started())
{
_time.sec += 1;
boost::thread::sleep(_time);
if(started())
std::cout << "." << std::flush;
}
}
}
private:
boost::xtime _time;
};
int main()
{
timer_func timer;
boost::thread t(timer);
while(true)
{
if(!started())
{
std::cout << "press enter to start: " << std::flush;
std::cin.get();
start();
std::cout << "starting" << std::endl;
start_condition.notify_one();
}
else
{
std::cout << "press enter to stop: " << std::flush;
std::cin.get();
stop();
std::cout << "stopping" << std::endl;
}
}
return 0;
}
Andrew Connell
Contact