src/Pure/Concurrent/single_assignment.ML
author wenzelm
Wed, 11 Apr 2012 13:37:46 +0200
changeset 47422 5832630f049a
parent 43761 e72ba84ae58f
child 59054 61b723761dff
permissions -rw-r--r--
tuned message;

(*  Title:      Pure/Concurrent/single_assignment.ML
    Author:     Makarius

Single-assignment variables with locking/signalling.
*)

signature SINGLE_ASSIGNMENT =
sig
  type 'a var
  val var: string -> 'a var
  val peek: 'a var -> 'a option
  val await: 'a var -> 'a
  val assign: 'a var -> 'a -> unit
end;

structure Single_Assignment: SINGLE_ASSIGNMENT =
struct

abstype 'a var = Var of
 {name: string,
  lock: Mutex.mutex,
  cond: ConditionVar.conditionVar,
  var: 'a SingleAssignment.saref}
with

fun var name = Var
 {name = name,
  lock = Mutex.mutex (),
  cond = ConditionVar.conditionVar (),
  var = SingleAssignment.saref ()};

fun peek (Var {var, ...}) = SingleAssignment.savalue var;

fun await (v as Var {name, lock, cond, ...}) =
  Simple_Thread.synchronized name lock (fn () =>
    let
      fun wait () =
        (case peek v of
          NONE =>
            (case Multithreading.sync_wait NONE NONE cond lock of
              Exn.Res _ => wait ()
            | Exn.Exn exn => reraise exn)
        | SOME x => x);
    in wait () end);

fun assign (v as Var {name, lock, cond, var}) x =
  Simple_Thread.synchronized name lock (fn () =>
    (case peek v of
      SOME _ => raise Fail ("Duplicate assignment to " ^ name)
    | NONE =>
        uninterruptible (fn _ => fn () =>
         (SingleAssignment.saset (var, x); ConditionVar.broadcast cond)) ()));

end;

end;