10.5 Delayed Evaluation
| import: rhombus/delay | package: rhombus-lib |
The rhombus/delay module implements delayed evaluation. A delay value contains an expression whose evaluation waits until the delay is forced with the Delay.force method. After the delay’s value is forced, further calls to Delay.force produce the same result.
annotation | ||||||||
| ||||||||
annotation | ||||||||
| ||||||||
| ||||||||
function | ||||||||
| ||||||||
expression | ||||||||
| ||||||||
| ||||||||
|
The Delay function creates a delay given a function of zero arguments to be called on demand to produce the value.
The delay form creates a delay that evaluates the body sequence on demand to obtain the delay’s value.
A delay is not thread-safe by default: concurrent attempts to force a delay can trigger an exception. Specify ~sync before the body of a delay form to create a delay that is thread-safe, in which case concurrent attempts to force the delay’s value causes all but one thread to wait until the result is ready.
> def d:
println("working")
1 + 2
> d.force()
working
3
> d.force()
3
Calling the Delay.force method on a delay that is currently being forced throws a “reentrant promise” exception. Use the ~sync kind in delay to create a delay that can be forced concurrently by multiple threads.
> def d:
"ok"
> d.force()
"ok"
> def d2:
d2.force()
> d2.force()
force: reentrant promise ‘...eference/delay.scrbl:93:4’
method | ||||
|
The pool argument is passed along to a use of thread, so it can be #'own or a ThreadPool to force the delay in parallel, instead of merely concurrently.
> def d1:
1
> def d2:
Evt.system_idle.sync()
2
1
method | |
| |
method | |
The Delay.is_running method reports whether dly is currently being forced, in which case dly.force() will throw an exception.