crossbeam-rs / crossbeam

Tools for concurrent programming in Rust
Apache License 2.0
7.48k stars 471 forks source link

Channel timeouts based on deadlines instead of durations #1117

Closed mmottl closed 5 months ago

mmottl commented 5 months ago

It seems the design of timeouts could be improved by using deadlines (absolute time) instead of durations (relative time).

If you look at the Open Group standard specification of pthread_cond_timedwait, they explain the reasoning why they chose absolute instead of relative timeouts:

Timed Wait Semantics

An absolute time measure was chosen for specifying the timeout parameter for two reasons. First, a relative time measure can be easily implemented on top of a function that specifies absolute time, but there is a race condition associated with specifying an absolute timeout on top of a function that specifies relative timeouts. For example, assume that clock_gettime() returns the current time and cond_relative_timed_wait() uses relative timeouts:

clock_gettime(CLOCK_REALTIME, &now) reltime = sleep_til_this_absolute_time -now; cond_relative_timed_wait(c, m, &reltime);

If the thread is preempted between the first statement and the last statement, the thread blocks for too long. Blocking, however, is irrelevant if an absolute timeout is used. An absolute timeout also need not be recomputed if it is used multiple times in a loop, such as that enclosing a condition wait.

For cases when the system clock is advanced discontinuously by an operator, it is expected that implementations process any timed wait expiring at an intervening time as if that time had actually occurred.

I'm not sure how much effort it would be to provide this feature, but it would certainly simplify some user code and make it more robust.

mmottl commented 5 months ago

It seems I missed some part of the documentation, it is apparently possible.