Node:Fluids, Previous:Threads, Up:Scheduling

32.5 Fluids

Fluids are objects to store values in. They have a few properties which make them useful in certain situations: Fluids can have one value per dynamic root (see Dynamic Roots), so that changes to the value in a fluid are only visible in the same dynamic root. Since threads are executed in separate dynamic roots, fluids can be used for thread local storage (see Threads).

Fluids can be used to simulate dynamically scoped variables. These are used in several (especially in older) dialects of lisp, such as in Emacs Lisp, and they work a bit like global variables in that they can be modified by the caller of a procedure, and the called procedure will see the changes. With lexically scoped variables--which are normally used in Scheme--this cannot happen. See the description of with-fluids* below for details.

New fluids are created with make-fluid and fluid? is used for testing whether an object is actually a fluid.

make-fluid Scheme Procedure
scm_make_fluid () C Function
Return a newly created fluid. Fluids are objects of a certain type (a smob) that can hold one SCM value per dynamic root. That is, modifications to this value are only visible to code that executes within the same dynamic root as the modifying code. When a new dynamic root is constructed, it inherits the values from its parent. Because each thread executes in its own dynamic root, you can use fluids for thread local storage.

fluid? obj Scheme Procedure
scm_fluid_p (obj) C Function
Return #t iff obj is a fluid; otherwise, return #f.

The values stored in a fluid can be accessed with fluid-ref and fluid-set!.

fluid-ref fluid Scheme Procedure
scm_fluid_ref (fluid) C Function
Return the value associated with fluid in the current dynamic root. If fluid has not been set, then return #f.

fluid-set! fluid value Scheme Procedure
scm_fluid_set_x (fluid, value) C Function
Set the value associated with fluid in the current dynamic root.

with-fluids* temporarily changes the values of one or more fluids, so that the given procedure and each procedure called by it access the given values. After the procedure returns, the old values are restored.

with-fluids* fluids values thunk Scheme Procedure
scm_with_fluids (fluids, values, thunk) C Function
Set fluids to values temporary, and call thunk. fluids must be a list of fluids and values must be the same number of their values to be applied. Each substitution is done one after another. thunk must be a procedure with no argument.