Boost logo

Boost Users :

From: Ian McCulloch (ianmcc_at_[hidden])
Date: 2006-10-12 09:39:48


Roland Schwarz wrote:

> Sascha Seewald wrote:
>> What about adding a function boost::sleep_until() that takes a point in
>> time and change boost::sleep() to take a duration?
>
> I believe the choice was done deliberately, and is more generic.
> Altough you might not see much use for it, it will allow creating
> predictable behavior.

The problem is, that in most cases boost::sleep() converts the absolute time
into a relative time anyway, and this is a race condition (if the thread is
interrupted after retrieving the current time, but before the relative
duration is calculated, you end up sleeping too long). You can convert a
relative time into an absolute time safely, but not the other way around.
Maybe this doesn't matter for sleep(), if you can't (or don't need to)
distinguish between a thread sleep()ing and a thread that is preempted.

[snip example where absolute time sleep is used]

> 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);
> }

Right. But the opposite applies too: given a relative sleep function you
can write an absolute sleep just as easily (with the caveat that there is a
race condition and you might sleep too long) - which is exactly what
boost::thread::sleep() does most of the time anyway.

>
> 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.

Well, if you really cared about getting an accurate absolute sleep it would
be in the context of a condition variable timed wait, in which case sleep()
is not the right function anyway. The primitive in this case is some
variant of the operating system sleep system call, which AFAIK always takes
a relative time.

Cheers,
Ian McCulloch


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