Boost logo

Boost Users :

From: Tobias Schwinger (tschwinger_at_[hidden])
Date: 2007-06-18 05:52:47


me22 wrote:
> On 16/06/07, Meryl Silverburgh <silverburgh.meryl_at_[hidden]> wrote:
>> Can you please tell me if i can do this with boost::thread library?
>> 1. create a timer (say 5 seconds) which execute a function in a
>> different thread when it expires.
>> 2. the creator can cancel the timer before it expires.
>>
> It's not premade, but you could do it easily enough. Start a thread
> which will wait (until an xtime), then call a function (stored in a
> boost::function<void()> perhaps), so long as a flag isn't set (you
> could make that in a shared_ptr<bool> to avoid lifetime worries).

That works. However, it's nicer to use a 'condition' instead of a global
flag and a 'timed_wait' on that condition to put the thread asleep.

This way the condition will wake up the thread so it can be reused.

I'll attach a simple "interval timer" that uses a condition variable to
terminate the thread. Changing it to the "stop watch timer" described in
the OP should be a matter of just adding some more conditions.

Regards,
Tobias


#include <string>
#include <iostream>

#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/noncopyable.hpp>

class timer : boost::noncopyable
{
    boost::xtime wait_time, next_time;
    boost::mutex monitor;
    boost::condition aborted;
    boost::thread thread;
public:

    explicit timer(boost::xtime const & interval)
      : wait_time(interval)
      , thread( boost::bind(& timer::thread_body, this) )
    { }

    ~timer()
    {
        aborted.notify_one();
        thread.join();
    }

private:

    void calc_next_time()
    {
        boost::xtime_get(& next_time, boost::TIME_UTC);
        next_time.sec += wait_time.sec;
        next_time.nsec += wait_time.nsec;
        next_time.sec += next_time.nsec / 1000000000;
        next_time.nsec %= 1000000000;
    }

    void thread_body()
    {
        boost::mutex::scoped_lock lock(monitor);

        for (;;)
        {
            calc_next_time();
            if (aborted.timed_wait(lock, next_time)) break;
            std::cout << "event" << std::endl;
        }
    }
};

int main()
{
    boost::xtime interval = { 0, 200000000 };

    timer t(interval);

    std::string s;
    std::getline(std::cin, s);

    return 0;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net