Boost logo

Boost Users :

From: Johan Nilsson (r.johan.nilsson_at_[hidden])
Date: 2006-10-12 09:48:23


Roland Schwarz wrote:

[snip]

>
> while(true) {
> ... do something ...
> relative_sleep(10);
>
> }
>
> you can see easily that you will accumulate an error from each
> run of the loop.
>
> boost::xtime xt;
> boost::xtime_get(xt);
> xt.sec += 10;
> while(true) {
> ... do something ...
> boost::thread::sleep(xt);
> xt.sec += 10;
> }
>
> you can see now that this works smoothly (of course ... do something
> ... will be assumed to last < 10 sec)

Perhaps, but this method is susceptible to race conditions. System time can
(naturally) get changed by e.g. ntpd or Windows Time at any point -
including between xt.sec += 10 and thread::sleep() above, as well as during
the actual sleep.

>
> You can always easily write a little relative sleep if you need
> along the lines:
>
> void sleep(int sec) {
> boost::xtime xt;
> boost::xtime_get(xt);
> xt.sec += sec;
> boost::thread::sleep(xt);
> }
>

And if you like to sleep for less than 1 sec, you'll also need to manipulate
the nsec member. Not really hard to fix, but another potential source for
bugs.

Overloading sleep to allow using date_time's posix_time and time_duration as
well as xtime would be an alternative.

>
> Please don't forget: the threading library supply you with the
> essential primitives. You might always need to create other
> convenience functions if needed. You cannot get the behaviour from
> the example when only a relative sleep is available.

That is true, but allowing a time_duration or being able to call e.g.
thread::sleep(xt, TIME_RELATIVE) would certainly make things easier.

/ Johan


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