src/Pure/Concurrent/simple_thread.ML
author wenzelm
Tue, 10 Nov 2009 23:15:15 +0100
changeset 33602 d25e6bd6ca95
parent 33220 11a1af478dac
child 33605 f91ec14e20b6
permissions -rw-r--r--
exported SimpleThread.attributes;
     1 (*  Title:      Pure/Concurrent/simple_thread.ML
     2     Author:     Makarius
     3 
     4 Simplified thread operations.
     5 *)
     6 
     7 signature SIMPLE_THREAD =
     8 sig
     9   val attributes: bool -> Thread.threadAttribute list
    10   val fork: bool -> (unit -> unit) -> Thread.thread
    11   val interrupt: Thread.thread -> unit
    12   val synchronized: string -> Mutex.mutex -> (unit -> 'a) -> 'a
    13 end;
    14 
    15 structure SimpleThread: SIMPLE_THREAD =
    16 struct
    17 
    18 fun attributes interrupts =
    19   if interrupts then Multithreading.public_interrupts else Multithreading.no_interrupts;
    20 
    21 fun fork interrupts body =
    22   Thread.fork (fn () => exception_trace (fn () => body () handle Exn.Interrupt => ()),
    23     attributes interrupts);
    24 
    25 fun interrupt thread = Thread.interrupt thread handle Thread _ => ();
    26 
    27 
    28 (* basic synchronization *)
    29 
    30 fun synchronized name lock e = Exn.release (uninterruptible (fn restore_attributes => fn () =>
    31   let
    32     val immediate =
    33       if Mutex.trylock lock then true
    34       else
    35         let
    36           val _ = Multithreading.tracing 5 (fn () => name ^ ": locking ...");
    37           val time = Multithreading.real_time Mutex.lock lock;
    38           val _ = Multithreading.tracing_time true time
    39             (fn () => name ^ ": locked after " ^ Time.toString time);
    40         in false end;
    41     val result = Exn.capture (restore_attributes e) ();
    42     val _ =
    43       if immediate then () else Multithreading.tracing 5 (fn () => name ^ ": unlocking ...");
    44     val _ = Mutex.unlock lock;
    45   in result end) ());
    46 
    47 end;