src/Pure/Concurrent/future.ML
author wenzelm
Mon Sep 29 21:26:46 2008 +0200 (2008-09-29 ago)
changeset 28415 bf08f955e7db
parent 28390 0b9fb63b8e1d
child 28430 29b2886114fb
permissions -rw-r--r--
added str_of;
wenzelm@28156
     1
(*  Title:      Pure/Concurrent/future.ML
wenzelm@28156
     2
    ID:         $Id$
wenzelm@28156
     3
    Author:     Makarius
wenzelm@28156
     4
wenzelm@28201
     5
Future values.
wenzelm@28201
     6
wenzelm@28201
     7
Notes:
wenzelm@28201
     8
wenzelm@28201
     9
  * Futures are similar to delayed evaluation, i.e. delay/force is
wenzelm@28201
    10
    generalized to fork/join (and variants).  The idea is to model
wenzelm@28201
    11
    parallel value-oriented computations, but *not* communicating
wenzelm@28201
    12
    processes.
wenzelm@28201
    13
wenzelm@28201
    14
  * Futures are grouped; failure of one group member causes the whole
wenzelm@28201
    15
    group to be interrupted eventually.
wenzelm@28201
    16
wenzelm@28201
    17
  * Forked futures are evaluated spontaneously by a farm of worker
wenzelm@28201
    18
    threads in the background; join resynchronizes the computation and
wenzelm@28201
    19
    delivers results (values or exceptions).
wenzelm@28201
    20
wenzelm@28201
    21
  * The pool of worker threads is limited, usually in correlation with
wenzelm@28201
    22
    the number of physical cores on the machine.  Note that allocation
wenzelm@28201
    23
    of runtime resources is distorted either if workers yield CPU time
wenzelm@28201
    24
    (e.g. via system sleep or wait operations), or if non-worker
wenzelm@28201
    25
    threads contend for significant runtime resources independently.
wenzelm@28156
    26
*)
wenzelm@28156
    27
wenzelm@28156
    28
signature FUTURE =
wenzelm@28156
    29
sig
wenzelm@28166
    30
  type task = TaskQueue.task
wenzelm@28166
    31
  type group = TaskQueue.group
wenzelm@28386
    32
  val thread_data: unit -> (string * task * group) option
wenzelm@28156
    33
  type 'a T
wenzelm@28166
    34
  val task_of: 'a T -> task
wenzelm@28177
    35
  val group_of: 'a T -> group
wenzelm@28415
    36
  val str_of: 'a T -> string
wenzelm@28320
    37
  val is_finished: 'a T -> bool
wenzelm@28304
    38
  val future: group option -> task list -> bool -> (unit -> 'a) -> 'a T
wenzelm@28166
    39
  val fork: (unit -> 'a) -> 'a T
wenzelm@28304
    40
  val fork_irrelevant: (unit -> 'a) -> 'a T
wenzelm@28193
    41
  val join_results: 'a T list -> 'a Exn.result list
wenzelm@28166
    42
  val join: 'a T -> 'a
wenzelm@28382
    43
  val release_results: 'a Exn.result list -> 'a list
wenzelm@28202
    44
  val focus: task list -> unit
wenzelm@28206
    45
  val interrupt_task: string -> unit
wenzelm@28197
    46
  val cancel: 'a T -> unit
wenzelm@28203
    47
  val shutdown: unit -> unit
wenzelm@28156
    48
end;
wenzelm@28156
    49
wenzelm@28156
    50
structure Future: FUTURE =
wenzelm@28156
    51
struct
wenzelm@28156
    52
wenzelm@28177
    53
(** future values **)
wenzelm@28177
    54
wenzelm@28167
    55
(* identifiers *)
wenzelm@28167
    56
wenzelm@28167
    57
type task = TaskQueue.task;
wenzelm@28167
    58
type group = TaskQueue.group;
wenzelm@28167
    59
wenzelm@28386
    60
local val tag = Universal.tag () : (string * task * group) option Universal.tag in
wenzelm@28177
    61
  fun thread_data () = the_default NONE (Thread.getLocal tag);
wenzelm@28390
    62
  fun setmp_thread_data data f x = Library.setmp_thread_data tag (thread_data ()) (SOME data) f x;
wenzelm@28167
    63
end;
wenzelm@28167
    64
wenzelm@28167
    65
wenzelm@28167
    66
(* datatype future *)
wenzelm@28167
    67
wenzelm@28167
    68
datatype 'a T = Future of
wenzelm@28167
    69
 {task: task,
wenzelm@28177
    70
  group: group,
wenzelm@28167
    71
  result: 'a Exn.result option ref};
wenzelm@28167
    72
wenzelm@28167
    73
fun task_of (Future {task, ...}) = task;
wenzelm@28167
    74
fun group_of (Future {group, ...}) = group;
wenzelm@28167
    75
wenzelm@28415
    76
fun str_of (Future {result, ...}) =
wenzelm@28415
    77
  (case ! result of
wenzelm@28415
    78
    NONE => "<future>"
wenzelm@28415
    79
  | SOME (Exn.Result _) => "<finished future>"
wenzelm@28415
    80
  | SOME (Exn.Exn _) => "<failed future>");
wenzelm@28415
    81
wenzelm@28320
    82
fun is_finished (Future {result, ...}) = is_some (! result);
wenzelm@28320
    83
wenzelm@28167
    84
wenzelm@28177
    85
wenzelm@28177
    86
(** scheduling **)
wenzelm@28177
    87
wenzelm@28177
    88
(* global state *)
wenzelm@28177
    89
wenzelm@28177
    90
val queue = ref TaskQueue.empty;
wenzelm@28192
    91
val workers = ref ([]: (Thread.thread * bool) list);
wenzelm@28177
    92
val scheduler = ref (NONE: Thread.thread option);
wenzelm@28177
    93
val excessive = ref 0;
wenzelm@28206
    94
val canceled = ref ([]: TaskQueue.group list);
wenzelm@28206
    95
val do_shutdown = ref false;
wenzelm@28177
    96
wenzelm@28177
    97
wenzelm@28177
    98
(* synchronization *)
wenzelm@28156
    99
wenzelm@28156
   100
local
wenzelm@28156
   101
  val lock = Mutex.mutex ();
wenzelm@28156
   102
  val cond = ConditionVar.conditionVar ();
wenzelm@28156
   103
in
wenzelm@28156
   104
wenzelm@28192
   105
fun SYNCHRONIZED name e = uninterruptible (fn restore_attributes => fn () =>
wenzelm@28162
   106
  let
wenzelm@28380
   107
    val _ = Multithreading.tracing 3 (fn () => name ^ ": locking");
wenzelm@28162
   108
    val _ = Mutex.lock lock;
wenzelm@28380
   109
    val _ = Multithreading.tracing 3 (fn () => name ^ ": locked");
wenzelm@28162
   110
    val result = Exn.capture (restore_attributes e) ();
wenzelm@28162
   111
    val _ = Mutex.unlock lock;
wenzelm@28380
   112
    val _ = Multithreading.tracing 3 (fn () => name ^ ": unlocked");
wenzelm@28162
   113
  in Exn.release result end) ();
wenzelm@28156
   114
wenzelm@28167
   115
fun wait name = (*requires SYNCHRONIZED*)
wenzelm@28206
   116
  ConditionVar.wait (cond, lock);
wenzelm@28206
   117
wenzelm@28206
   118
fun wait_timeout name timeout = (*requires SYNCHRONIZED*)
wenzelm@28206
   119
  ConditionVar.waitUntil (cond, lock, Time.+ (Time.now (), timeout));
wenzelm@28166
   120
wenzelm@28166
   121
fun notify_all () = (*requires SYNCHRONIZED*)
wenzelm@28166
   122
  ConditionVar.broadcast cond;
wenzelm@28156
   123
wenzelm@28156
   124
end;
wenzelm@28156
   125
wenzelm@28156
   126
wenzelm@28382
   127
(* worker activity *)
wenzelm@28382
   128
wenzelm@28382
   129
fun trace_active () =
wenzelm@28382
   130
  let
wenzelm@28382
   131
    val ws = ! workers;
wenzelm@28382
   132
    val m = string_of_int (length ws);
wenzelm@28382
   133
    val n = string_of_int (length (filter #2 ws));
wenzelm@28382
   134
  in Multithreading.tracing 1 (fn () => "SCHEDULE: " ^ m ^ " workers, " ^ n ^ " active") end;
wenzelm@28382
   135
wenzelm@28382
   136
fun change_active active = (*requires SYNCHRONIZED*)
wenzelm@28382
   137
  change workers (AList.update Thread.equal (Thread.self (), active));
wenzelm@28382
   138
wenzelm@28382
   139
wenzelm@28177
   140
(* execute *)
wenzelm@28156
   141
wenzelm@28167
   142
fun execute name (task, group, run) =
wenzelm@28167
   143
  let
wenzelm@28382
   144
    val _ = trace_active ();
wenzelm@28380
   145
    val _ = Multithreading.tracing 3 (fn () => name ^ ": running");
wenzelm@28390
   146
    val ok = setmp_thread_data (name, task, group) run ();
wenzelm@28380
   147
    val _ = Multithreading.tracing 3 (fn () => name ^ ": finished");
wenzelm@28192
   148
    val _ = SYNCHRONIZED "execute" (fn () =>
wenzelm@28177
   149
     (change queue (TaskQueue.finish task);
wenzelm@28186
   150
      if ok then ()
wenzelm@28191
   151
      else if TaskQueue.cancel (! queue) group then ()
wenzelm@28206
   152
      else change canceled (cons group);
wenzelm@28177
   153
      notify_all ()));
wenzelm@28167
   154
  in () end;
wenzelm@28167
   155
wenzelm@28167
   156
wenzelm@28167
   157
(* worker threads *)
wenzelm@28167
   158
wenzelm@28186
   159
fun worker_wait name = (*requires SYNCHRONIZED*)
wenzelm@28186
   160
  (change_active false; wait name; change_active true);
wenzelm@28162
   161
wenzelm@28167
   162
fun worker_next name = (*requires SYNCHRONIZED*)
wenzelm@28167
   163
  if ! excessive > 0 then
wenzelm@28167
   164
    (dec excessive;
wenzelm@28192
   165
     change workers (filter_out (fn (thread, _) => Thread.equal (thread, Thread.self ())));
wenzelm@28203
   166
     notify_all ();
wenzelm@28167
   167
     NONE)
wenzelm@28166
   168
  else
wenzelm@28186
   169
    (case change_result queue TaskQueue.dequeue of
wenzelm@28186
   170
      NONE => (worker_wait name; worker_next name)
wenzelm@28166
   171
    | some => some);
wenzelm@28156
   172
wenzelm@28167
   173
fun worker_loop name =
wenzelm@28192
   174
  (case SYNCHRONIZED name (fn () => worker_next name) of
wenzelm@28380
   175
    NONE => Multithreading.tracing 3 (fn () => name ^ ": exit")
wenzelm@28167
   176
  | SOME work => (execute name work; worker_loop name));
wenzelm@28156
   177
wenzelm@28167
   178
fun worker_start name = (*requires SYNCHRONIZED*)
wenzelm@28242
   179
  change workers (cons (SimpleThread.fork false (fn () => worker_loop name), true));
wenzelm@28156
   180
wenzelm@28156
   181
wenzelm@28156
   182
(* scheduler *)
wenzelm@28156
   183
wenzelm@28206
   184
fun scheduler_next () = (*requires SYNCHRONIZED*)
wenzelm@28156
   185
  let
wenzelm@28206
   186
    (*worker threads*)
wenzelm@28191
   187
    val _ =
wenzelm@28192
   188
      (case List.partition (Thread.isActive o #1) (! workers) of
wenzelm@28191
   189
        (_, []) => ()
wenzelm@28191
   190
      | (active, inactive) =>
wenzelm@28191
   191
          (workers := active; Multithreading.tracing 0 (fn () =>
wenzelm@28192
   192
            "SCHEDULE: disposed " ^ string_of_int (length inactive) ^ " dead worker threads")));
wenzelm@28382
   193
    val _ = trace_active ();
wenzelm@28191
   194
wenzelm@28206
   195
    val m = if ! do_shutdown then 0 else Multithreading.max_threads_value ();
wenzelm@28167
   196
    val l = length (! workers);
wenzelm@28167
   197
    val _ = excessive := l - m;
wenzelm@28203
   198
    val _ =
wenzelm@28203
   199
      if m > l then funpow (m - l) (fn () => worker_start ("worker " ^ serial_string ())) ()
wenzelm@28203
   200
      else ();
wenzelm@28206
   201
wenzelm@28206
   202
    (*canceled groups*)
wenzelm@28206
   203
    val _ =  change canceled (filter_out (TaskQueue.cancel (! queue)));
wenzelm@28206
   204
wenzelm@28206
   205
    (*shutdown*)
wenzelm@28206
   206
    val continue = not (! do_shutdown andalso null (! workers));
wenzelm@28206
   207
    val _ = if continue then () else scheduler := NONE;
wenzelm@28167
   208
wenzelm@28206
   209
    val _ = notify_all ();
wenzelm@28206
   210
    val _ = wait_timeout "scheduler" (Time.fromSeconds 1);
wenzelm@28206
   211
  in continue end;
wenzelm@28206
   212
wenzelm@28206
   213
fun scheduler_loop () =
wenzelm@28206
   214
 (while SYNCHRONIZED "scheduler" scheduler_next do ();
wenzelm@28380
   215
  Multithreading.tracing 3 (fn () => "scheduler: exit"));
wenzelm@28156
   216
wenzelm@28203
   217
fun scheduler_active () = (*requires SYNCHRONIZED*)
wenzelm@28203
   218
  (case ! scheduler of NONE => false | SOME thread => Thread.isActive thread);
wenzelm@28203
   219
wenzelm@28192
   220
fun scheduler_check () = SYNCHRONIZED "scheduler_check" (fn () =>
wenzelm@28206
   221
  if not (scheduler_active ()) then
wenzelm@28386
   222
    (Multithreading.tracing 3 (fn () => "scheduler: fork");
wenzelm@28386
   223
     do_shutdown := false; scheduler := SOME (SimpleThread.fork false scheduler_loop))
wenzelm@28206
   224
  else if ! do_shutdown then error "Scheduler shutdown in progress"
wenzelm@28206
   225
  else ());
wenzelm@28156
   226
wenzelm@28156
   227
wenzelm@28191
   228
(* future values: fork independent computation *)
wenzelm@28156
   229
wenzelm@28304
   230
fun future opt_group deps pri (e: unit -> 'a) =
wenzelm@28156
   231
  let
wenzelm@28191
   232
    val _ = scheduler_check ();
wenzelm@28177
   233
wenzelm@28191
   234
    val group = (case opt_group of SOME group => group | NONE => TaskQueue.new_group ());
wenzelm@28177
   235
wenzelm@28166
   236
    val result = ref (NONE: 'a Exn.result option);
wenzelm@28177
   237
    val run = Multithreading.with_attributes (Thread.getAttributes ())
wenzelm@28177
   238
      (fn _ => fn ok =>
wenzelm@28177
   239
        let val res = if ok then Exn.capture e () else Exn.Exn Interrupt
wenzelm@28177
   240
        in result := SOME res; is_some (Exn.get_result res) end);
wenzelm@28177
   241
wenzelm@28192
   242
    val task = SYNCHRONIZED "future" (fn () =>
wenzelm@28304
   243
      change_result queue (TaskQueue.enqueue group deps pri run) before notify_all ());
wenzelm@28166
   244
  in Future {task = task, group = group, result = result} end;
wenzelm@28162
   245
wenzelm@28386
   246
fun fork e = future (Option.map #3 (thread_data ())) [] true e;
wenzelm@28386
   247
fun fork_irrelevant e = future (Option.map #3 (thread_data ())) [] false e;
wenzelm@28186
   248
wenzelm@28186
   249
wenzelm@28191
   250
(* join: retrieve results *)
wenzelm@28186
   251
wenzelm@28331
   252
fun join_results [] = []
wenzelm@28331
   253
  | join_results xs =
wenzelm@28331
   254
      let
wenzelm@28331
   255
        val _ = scheduler_check ();
wenzelm@28331
   256
        val _ = Multithreading.self_critical () andalso
wenzelm@28331
   257
          error "Cannot join future values within critical section";
wenzelm@28177
   258
wenzelm@28386
   259
        fun join_loop _ [] = ()
wenzelm@28386
   260
          | join_loop name tasks =
wenzelm@28386
   261
              (case SYNCHRONIZED name (fn () =>
wenzelm@28382
   262
                  change_result queue (TaskQueue.dequeue_towards tasks)) of
wenzelm@28382
   263
                NONE => ()
wenzelm@28386
   264
              | SOME (work, tasks') => (execute name work; join_loop name tasks'));
wenzelm@28331
   265
        val _ =
wenzelm@28331
   266
          (case thread_data () of
wenzelm@28382
   267
            NONE =>
wenzelm@28382
   268
              (*alien thread -- refrain from contending for resources*)
wenzelm@28382
   269
              while exists (not o is_finished) xs
wenzelm@28382
   270
              do SYNCHRONIZED "join_thread" (fn () => wait "join_thread")
wenzelm@28386
   271
          | SOME (name, task, _) =>
wenzelm@28382
   272
              (*proper task -- actively work towards results*)
wenzelm@28382
   273
              let
wenzelm@28382
   274
                val unfinished = xs |> map_filter
wenzelm@28382
   275
                  (fn Future {task, result = ref NONE, ...} => SOME task | _ => NONE);
wenzelm@28382
   276
                val _ = SYNCHRONIZED "join" (fn () =>
wenzelm@28382
   277
                  (change queue (TaskQueue.depend unfinished task); notify_all ()));
wenzelm@28386
   278
                val _ = join_loop ("join_loop: " ^ name) unfinished;
wenzelm@28382
   279
                val _ =
wenzelm@28382
   280
                  while exists (not o is_finished) xs
wenzelm@28382
   281
                  do SYNCHRONIZED "join_task" (fn () => worker_wait "join_task");
wenzelm@28382
   282
              in () end);
wenzelm@28186
   283
wenzelm@28331
   284
      in xs |> map (fn Future {result = ref (SOME res), ...} => res) end;
wenzelm@28186
   285
wenzelm@28193
   286
fun join x = Exn.release (singleton join_results x);
wenzelm@28156
   287
wenzelm@28191
   288
wenzelm@28382
   289
(* release results *)
wenzelm@28382
   290
wenzelm@28382
   291
fun proper_exn (Exn.Result _) = NONE
wenzelm@28382
   292
  | proper_exn (Exn.Exn Interrupt) = NONE
wenzelm@28382
   293
  | proper_exn (Exn.Exn exn) = SOME exn;
wenzelm@28382
   294
wenzelm@28382
   295
fun release_results results =
wenzelm@28382
   296
  (case get_first proper_exn results of
wenzelm@28382
   297
    SOME exn => raise exn
wenzelm@28382
   298
  | NONE => List.map Exn.release results);
wenzelm@28382
   299
wenzelm@28382
   300
wenzelm@28202
   301
(* misc operations *)
wenzelm@28202
   302
wenzelm@28202
   303
(*focus: collection of high-priority task*)
wenzelm@28202
   304
fun focus tasks = SYNCHRONIZED "interrupt" (fn () =>
wenzelm@28202
   305
  change queue (TaskQueue.focus tasks));
wenzelm@28191
   306
wenzelm@28202
   307
(*interrupt: permissive signal, may get ignored*)
wenzelm@28197
   308
fun interrupt_task id = SYNCHRONIZED "interrupt"
wenzelm@28197
   309
  (fn () => TaskQueue.interrupt_external (! queue) id);
wenzelm@28191
   310
wenzelm@28206
   311
(*cancel: present and future group members will be interrupted eventually*)
wenzelm@28206
   312
fun cancel x =
wenzelm@28208
   313
 (scheduler_check ();
wenzelm@28208
   314
  SYNCHRONIZED "cancel" (fn () => (change canceled (cons (group_of x)); notify_all ())));
wenzelm@28206
   315
wenzelm@28206
   316
wenzelm@28203
   317
(*global join and shutdown*)
wenzelm@28203
   318
fun shutdown () =
wenzelm@28276
   319
  if Multithreading.available then
wenzelm@28276
   320
   (scheduler_check ();
wenzelm@28276
   321
    SYNCHRONIZED "shutdown" (fn () =>
wenzelm@28276
   322
     (while not (scheduler_active ()) do wait "shutdown: scheduler inactive";
wenzelm@28276
   323
      while not (TaskQueue.is_empty (! queue)) do wait "shutdown: join";
wenzelm@28276
   324
      do_shutdown := true;
wenzelm@28276
   325
      notify_all ();
wenzelm@28276
   326
      while not (null (! workers)) do wait "shutdown: workers";
wenzelm@28276
   327
      while scheduler_active () do wait "shutdown: scheduler still active")))
wenzelm@28276
   328
  else ();
wenzelm@28203
   329
wenzelm@28156
   330
end;