Gary Wessle wrote:
Hi
struct thread_alarm
{
thread_alarm(int secs) : m_secs(secs) { }
void operator()()
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += m_secs;
boost::thread::sleep(xt);
cout is not synchronized, it might
overlap with main thread's output
<snip>
std::cout << "alarm sounded..." << std::endl;
}
<snip>
switch( opt ) {
case ( 1 ): {
thread_alarm alarm(secs);
boost::thread thrd(alarm);
join will wait till thrd terminates, that doesn't seem
to be what you want
thrd.join();
break;
}
case (99 ): cout << "Exiting ...\n"; break;
default: cout << "you typed " << opt << endl;
I believe you want the alarm to sound if the user
takes more than 5 seconds to type
In that case you will need to cancel the alarm
here. your current implementation of thread_alarm
doesn't provide such functionality
maybe looping around a flag for a fraction
of alarm time and then changing the flag
to exit the loop would do.
general idea:
struct thread_alarm
{
bool loop_;
thread_alarm(int secs) : m_secs(secs) , loop_(true){ }
void cancel(){ loop_= false; }
void operator()()
{
while(loop_ && m_secs)
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
// sleep a second at a time
xt.sec += 1;
--m_secs;
boost::thread::sleep(xt);
}
if(loop_)
std::cout << "alarm sounded..." << std::endl;
}
int m_secs;
};