Ruby: future and delayed (lazy) variables

Future variables

Future variables are a very popular technique to implement dataflow execution. A future variable gets assigned with a (potentially lengthy) operation which will be executed in a separated thread. The assignment is therefore non-blocking.

As soon as the variable gets read, it blocks if the calculation isn’t ready, or it immediately returns the result.

I’ve implemented that feature using some Ruby tricks, but the finest and most elegant solution would be in Lisp using it’s unique macros.

Anyways, here a quick example:

x = RFuture.future do
   # some lengthy operation with an interesting result

Now, that assignment doesn’t block, and we could do some other things, later on we may want to know what the result of our operation is:

puts x

This code could block if the result isn’t ready.

As you can see, there is no special handling for reading the variable (meaning using adopting future variables later on is quite easy).

In the best case scenario the saved execution time is pretty high (compared to sequential processing):

Delayed (lazy) variables

Another concept introduced in this library are delayed or lazy variables. These are variables which get assigned a operation which isn’t executed until we really need the result. Seems pretty pointless, but it’s used in some functional programming languages (like Hasekll).

x = RFuture.delay do
   # some operation with an interesting result we may need later on

Again, reading the variable doesn’t differ from usual variables:

puts x

Download the file here.

From a programmer’s point of view, the user is a peripheral that types when you issue a read request.
— P. Williams