src/Pure/Concurrent/future.ML
author wenzelm
Tue Dec 16 12:13:53 2008 +0100 (2008-12-16 ago)
changeset 29118 8f2481aa363d
parent 28997 1b99dcae2156
child 29119 99941fd0cb0e
permissions -rw-r--r--
removed old scheduler;
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@28645
    30
  val enabled: unit -> bool
wenzelm@28166
    31
  type task = TaskQueue.task
wenzelm@28166
    32
  type group = TaskQueue.group
wenzelm@28979
    33
  val thread_data: unit -> (string * task) option
wenzelm@28972
    34
  type 'a future
wenzelm@28972
    35
  val task_of: 'a future -> task
wenzelm@28972
    36
  val group_of: 'a future -> group
wenzelm@28972
    37
  val peek: 'a future -> 'a Exn.result option
wenzelm@28972
    38
  val is_finished: 'a future -> bool
wenzelm@28997
    39
  val value: 'a -> 'a future
wenzelm@28972
    40
  val fork: (unit -> 'a) -> 'a future
wenzelm@28979
    41
  val fork_group: group -> (unit -> 'a) -> 'a future
wenzelm@28979
    42
  val fork_deps: 'b future list -> (unit -> 'a) -> 'a future
wenzelm@28972
    43
  val fork_background: (unit -> 'a) -> 'a future
wenzelm@28972
    44
  val join_results: 'a future list -> 'a Exn.result list
wenzelm@28972
    45
  val join_result: 'a future -> 'a Exn.result
wenzelm@28972
    46
  val join: 'a future -> 'a
wenzelm@28972
    47
  val map: ('a -> 'b) -> 'a future -> 'b future
wenzelm@28202
    48
  val focus: task list -> unit
wenzelm@28206
    49
  val interrupt_task: string -> unit
wenzelm@28972
    50
  val cancel: 'a future -> unit
wenzelm@28203
    51
  val shutdown: unit -> unit
wenzelm@28156
    52
end;
wenzelm@28156
    53
wenzelm@28156
    54
structure Future: FUTURE =
wenzelm@28156
    55
struct
wenzelm@28156
    56
wenzelm@28177
    57
(** future values **)
wenzelm@28177
    58
wenzelm@28645
    59
fun enabled () =
wenzelm@29118
    60
  Multithreading.enabled () andalso
wenzelm@28645
    61
    not (Multithreading.self_critical ());
wenzelm@28645
    62
wenzelm@28645
    63
wenzelm@28167
    64
(* identifiers *)
wenzelm@28167
    65
wenzelm@28167
    66
type task = TaskQueue.task;
wenzelm@28167
    67
type group = TaskQueue.group;
wenzelm@28167
    68
wenzelm@28979
    69
local val tag = Universal.tag () : (string * task) option Universal.tag in
wenzelm@28177
    70
  fun thread_data () = the_default NONE (Thread.getLocal tag);
wenzelm@28390
    71
  fun setmp_thread_data data f x = Library.setmp_thread_data tag (thread_data ()) (SOME data) f x;
wenzelm@28167
    72
end;
wenzelm@28167
    73
wenzelm@28167
    74
wenzelm@28167
    75
(* datatype future *)
wenzelm@28167
    76
wenzelm@28972
    77
datatype 'a future = Future of
wenzelm@28167
    78
 {task: task,
wenzelm@28177
    79
  group: group,
wenzelm@28167
    80
  result: 'a Exn.result option ref};
wenzelm@28167
    81
wenzelm@28167
    82
fun task_of (Future {task, ...}) = task;
wenzelm@28167
    83
fun group_of (Future {group, ...}) = group;
wenzelm@28167
    84
wenzelm@28558
    85
fun peek (Future {result, ...}) = ! result;
wenzelm@28558
    86
fun is_finished x = is_some (peek x);
wenzelm@28320
    87
wenzelm@28997
    88
fun value x = Future
wenzelm@28997
    89
 {task = TaskQueue.new_task (),
wenzelm@28997
    90
  group = TaskQueue.new_group (),
wenzelm@28997
    91
  result = ref (SOME (Exn.Result x))};
wenzelm@28997
    92
wenzelm@28167
    93
wenzelm@28177
    94
wenzelm@28177
    95
(** scheduling **)
wenzelm@28177
    96
wenzelm@28177
    97
(* global state *)
wenzelm@28177
    98
wenzelm@28177
    99
val queue = ref TaskQueue.empty;
wenzelm@28468
   100
val next = ref 0;
wenzelm@28192
   101
val workers = ref ([]: (Thread.thread * bool) list);
wenzelm@28177
   102
val scheduler = ref (NONE: Thread.thread option);
wenzelm@28177
   103
val excessive = ref 0;
wenzelm@28206
   104
val canceled = ref ([]: TaskQueue.group list);
wenzelm@28206
   105
val do_shutdown = ref false;
wenzelm@28177
   106
wenzelm@28177
   107
wenzelm@28177
   108
(* synchronization *)
wenzelm@28156
   109
wenzelm@28156
   110
local
wenzelm@28156
   111
  val lock = Mutex.mutex ();
wenzelm@28156
   112
  val cond = ConditionVar.conditionVar ();
wenzelm@28156
   113
in
wenzelm@28156
   114
wenzelm@28575
   115
fun SYNCHRONIZED name = SimpleThread.synchronized name lock;
wenzelm@28156
   116
wenzelm@28167
   117
fun wait name = (*requires SYNCHRONIZED*)
wenzelm@28468
   118
 (Multithreading.tracing 3 (fn () => name ^ ": wait ...");
wenzelm@28206
   119
  ConditionVar.wait (cond, lock);
wenzelm@28468
   120
  Multithreading.tracing 3 (fn () => name ^ ": ... continue"));
wenzelm@28206
   121
wenzelm@28206
   122
fun wait_timeout name timeout = (*requires SYNCHRONIZED*)
wenzelm@28468
   123
 (Multithreading.tracing 3 (fn () => name ^ ": wait ...");
wenzelm@28206
   124
  ConditionVar.waitUntil (cond, lock, Time.+ (Time.now (), timeout));
wenzelm@28468
   125
  Multithreading.tracing 3 (fn () => name ^ ": ... continue"));
wenzelm@28166
   126
wenzelm@28166
   127
fun notify_all () = (*requires SYNCHRONIZED*)
wenzelm@28166
   128
  ConditionVar.broadcast cond;
wenzelm@28156
   129
wenzelm@28156
   130
end;
wenzelm@28156
   131
wenzelm@28156
   132
wenzelm@28382
   133
(* worker activity *)
wenzelm@28382
   134
wenzelm@28382
   135
fun trace_active () =
wenzelm@28382
   136
  let
wenzelm@28382
   137
    val ws = ! workers;
wenzelm@28382
   138
    val m = string_of_int (length ws);
wenzelm@28382
   139
    val n = string_of_int (length (filter #2 ws));
wenzelm@28382
   140
  in Multithreading.tracing 1 (fn () => "SCHEDULE: " ^ m ^ " workers, " ^ n ^ " active") end;
wenzelm@28382
   141
wenzelm@28382
   142
fun change_active active = (*requires SYNCHRONIZED*)
wenzelm@28382
   143
  change workers (AList.update Thread.equal (Thread.self (), active));
wenzelm@28382
   144
wenzelm@28382
   145
wenzelm@28177
   146
(* execute *)
wenzelm@28156
   147
wenzelm@28167
   148
fun execute name (task, group, run) =
wenzelm@28167
   149
  let
wenzelm@28382
   150
    val _ = trace_active ();
wenzelm@28979
   151
    val ok = setmp_thread_data (name, task) run ();
wenzelm@28192
   152
    val _ = SYNCHRONIZED "execute" (fn () =>
wenzelm@28177
   153
     (change queue (TaskQueue.finish task);
wenzelm@28186
   154
      if ok then ()
wenzelm@28191
   155
      else if TaskQueue.cancel (! queue) group then ()
wenzelm@28206
   156
      else change canceled (cons group);
wenzelm@28177
   157
      notify_all ()));
wenzelm@28167
   158
  in () end;
wenzelm@28167
   159
wenzelm@28167
   160
wenzelm@28167
   161
(* worker threads *)
wenzelm@28167
   162
wenzelm@28186
   163
fun worker_wait name = (*requires SYNCHRONIZED*)
wenzelm@28186
   164
  (change_active false; wait name; change_active true);
wenzelm@28162
   165
wenzelm@28167
   166
fun worker_next name = (*requires SYNCHRONIZED*)
wenzelm@28167
   167
  if ! excessive > 0 then
wenzelm@28167
   168
    (dec excessive;
wenzelm@28192
   169
     change workers (filter_out (fn (thread, _) => Thread.equal (thread, Thread.self ())));
wenzelm@28203
   170
     notify_all ();
wenzelm@28167
   171
     NONE)
wenzelm@28166
   172
  else
wenzelm@28186
   173
    (case change_result queue TaskQueue.dequeue of
wenzelm@28186
   174
      NONE => (worker_wait name; worker_next name)
wenzelm@28166
   175
    | some => some);
wenzelm@28156
   176
wenzelm@28167
   177
fun worker_loop name =
wenzelm@28192
   178
  (case SYNCHRONIZED name (fn () => worker_next name) of
wenzelm@28468
   179
    NONE => Multithreading.tracing 3 (fn () => name ^ ": exit")
wenzelm@28167
   180
  | SOME work => (execute name work; worker_loop name));
wenzelm@28156
   181
wenzelm@28167
   182
fun worker_start name = (*requires SYNCHRONIZED*)
wenzelm@28242
   183
  change workers (cons (SimpleThread.fork false (fn () => worker_loop name), true));
wenzelm@28156
   184
wenzelm@28156
   185
wenzelm@28156
   186
(* scheduler *)
wenzelm@28156
   187
wenzelm@28206
   188
fun scheduler_next () = (*requires SYNCHRONIZED*)
wenzelm@28156
   189
  let
wenzelm@28206
   190
    (*worker threads*)
wenzelm@28191
   191
    val _ =
wenzelm@28192
   192
      (case List.partition (Thread.isActive o #1) (! workers) of
wenzelm@28191
   193
        (_, []) => ()
wenzelm@28191
   194
      | (active, inactive) =>
wenzelm@28191
   195
          (workers := active; Multithreading.tracing 0 (fn () =>
wenzelm@28192
   196
            "SCHEDULE: disposed " ^ string_of_int (length inactive) ^ " dead worker threads")));
wenzelm@28382
   197
    val _ = trace_active ();
wenzelm@28191
   198
wenzelm@28206
   199
    val m = if ! do_shutdown then 0 else Multithreading.max_threads_value ();
wenzelm@28167
   200
    val l = length (! workers);
wenzelm@28167
   201
    val _ = excessive := l - m;
wenzelm@28203
   202
    val _ =
wenzelm@28468
   203
      if m > l then funpow (m - l) (fn () => worker_start ("worker " ^ string_of_int (inc next))) ()
wenzelm@28203
   204
      else ();
wenzelm@28206
   205
wenzelm@28206
   206
    (*canceled groups*)
wenzelm@28206
   207
    val _ =  change canceled (filter_out (TaskQueue.cancel (! queue)));
wenzelm@28206
   208
wenzelm@28206
   209
    (*shutdown*)
wenzelm@28206
   210
    val continue = not (! do_shutdown andalso null (! workers));
wenzelm@28206
   211
    val _ = if continue then () else scheduler := NONE;
wenzelm@28167
   212
wenzelm@28206
   213
    val _ = notify_all ();
wenzelm@28464
   214
    val _ = wait_timeout "scheduler" (Time.fromSeconds 3);
wenzelm@28206
   215
  in continue end;
wenzelm@28206
   216
wenzelm@28206
   217
fun scheduler_loop () =
wenzelm@28206
   218
 (while SYNCHRONIZED "scheduler" scheduler_next do ();
wenzelm@28534
   219
  Multithreading.tracing 3 (fn () => "scheduler: exit"));
wenzelm@28156
   220
wenzelm@28203
   221
fun scheduler_active () = (*requires SYNCHRONIZED*)
wenzelm@28203
   222
  (case ! scheduler of NONE => false | SOME thread => Thread.isActive thread);
wenzelm@28203
   223
wenzelm@28464
   224
fun scheduler_check name = SYNCHRONIZED name (fn () =>
wenzelm@28206
   225
  if not (scheduler_active ()) then
wenzelm@28534
   226
    (Multithreading.tracing 3 (fn () => "scheduler: fork");
wenzelm@28534
   227
     do_shutdown := false; scheduler := SOME (SimpleThread.fork false scheduler_loop))
wenzelm@28206
   228
  else if ! do_shutdown then error "Scheduler shutdown in progress"
wenzelm@28206
   229
  else ());
wenzelm@28156
   230
wenzelm@28156
   231
wenzelm@28191
   232
(* future values: fork independent computation *)
wenzelm@28156
   233
wenzelm@28304
   234
fun future opt_group deps pri (e: unit -> 'a) =
wenzelm@28156
   235
  let
wenzelm@28464
   236
    val _ = scheduler_check "future check";
wenzelm@28177
   237
wenzelm@28191
   238
    val group = (case opt_group of SOME group => group | NONE => TaskQueue.new_group ());
wenzelm@28177
   239
wenzelm@28166
   240
    val result = ref (NONE: 'a Exn.result option);
wenzelm@28177
   241
    val run = Multithreading.with_attributes (Thread.getAttributes ())
wenzelm@28177
   242
      (fn _ => fn ok =>
wenzelm@28532
   243
        let
wenzelm@28532
   244
          val res = if ok then Exn.capture e () else Exn.Exn Exn.Interrupt;
wenzelm@28548
   245
          val _ = result := SOME res;
wenzelm@28532
   246
          val res_ok =
wenzelm@28532
   247
            (case res of
wenzelm@28532
   248
              Exn.Result _ => true
wenzelm@28548
   249
            | Exn.Exn Exn.Interrupt => (TaskQueue.invalidate_group group; true)
wenzelm@28532
   250
            | _ => false);
wenzelm@28548
   251
        in res_ok end);
wenzelm@28177
   252
wenzelm@28192
   253
    val task = SYNCHRONIZED "future" (fn () =>
wenzelm@28304
   254
      change_result queue (TaskQueue.enqueue group deps pri run) before notify_all ());
wenzelm@28166
   255
  in Future {task = task, group = group, result = result} end;
wenzelm@28162
   256
wenzelm@28979
   257
fun fork e = future NONE [] true e;
wenzelm@28979
   258
fun fork_group group e = future (SOME group) [] true e;
wenzelm@28979
   259
fun fork_deps deps e = future NONE (map task_of deps) true e;
wenzelm@28979
   260
fun fork_background e = future NONE [] false e;
wenzelm@28186
   261
wenzelm@28186
   262
wenzelm@28191
   263
(* join: retrieve results *)
wenzelm@28186
   264
wenzelm@28331
   265
fun join_results [] = []
wenzelm@28532
   266
  | join_results xs = uninterruptible (fn _ => fn () =>
wenzelm@28331
   267
      let
wenzelm@28464
   268
        val _ = scheduler_check "join check";
wenzelm@28331
   269
        val _ = Multithreading.self_critical () andalso
wenzelm@28647
   270
          exists (not o is_finished) xs andalso
wenzelm@28331
   271
          error "Cannot join future values within critical section";
wenzelm@28177
   272
wenzelm@28386
   273
        fun join_loop _ [] = ()
wenzelm@28386
   274
          | join_loop name tasks =
wenzelm@28386
   275
              (case SYNCHRONIZED name (fn () =>
wenzelm@28382
   276
                  change_result queue (TaskQueue.dequeue_towards tasks)) of
wenzelm@28382
   277
                NONE => ()
wenzelm@28386
   278
              | SOME (work, tasks') => (execute name work; join_loop name tasks'));
wenzelm@28331
   279
        val _ =
wenzelm@28331
   280
          (case thread_data () of
wenzelm@28382
   281
            NONE =>
wenzelm@28382
   282
              (*alien thread -- refrain from contending for resources*)
wenzelm@28382
   283
              while exists (not o is_finished) xs
wenzelm@28382
   284
              do SYNCHRONIZED "join_thread" (fn () => wait "join_thread")
wenzelm@28979
   285
          | SOME (name, task) =>
wenzelm@28382
   286
              (*proper task -- actively work towards results*)
wenzelm@28382
   287
              let
wenzelm@28382
   288
                val unfinished = xs |> map_filter
wenzelm@28382
   289
                  (fn Future {task, result = ref NONE, ...} => SOME task | _ => NONE);
wenzelm@28382
   290
                val _ = SYNCHRONIZED "join" (fn () =>
wenzelm@28382
   291
                  (change queue (TaskQueue.depend unfinished task); notify_all ()));
wenzelm@28386
   292
                val _ = join_loop ("join_loop: " ^ name) unfinished;
wenzelm@28382
   293
                val _ =
wenzelm@28382
   294
                  while exists (not o is_finished) xs
wenzelm@28382
   295
                  do SYNCHRONIZED "join_task" (fn () => worker_wait "join_task");
wenzelm@28382
   296
              in () end);
wenzelm@28186
   297
wenzelm@28532
   298
      in xs |> map (fn Future {result = ref (SOME res), ...} => res) end) ();
wenzelm@28186
   299
wenzelm@28647
   300
fun join_result x = singleton join_results x;
wenzelm@28647
   301
fun join x = Exn.release (join_result x);
wenzelm@28156
   302
wenzelm@28979
   303
fun map f x = fork_deps [x] (fn () => f (join x));
wenzelm@28979
   304
wenzelm@28191
   305
wenzelm@28202
   306
(* misc operations *)
wenzelm@28202
   307
wenzelm@28202
   308
(*focus: collection of high-priority task*)
wenzelm@28464
   309
fun focus tasks = SYNCHRONIZED "focus" (fn () =>
wenzelm@28202
   310
  change queue (TaskQueue.focus tasks));
wenzelm@28191
   311
wenzelm@28202
   312
(*interrupt: permissive signal, may get ignored*)
wenzelm@28197
   313
fun interrupt_task id = SYNCHRONIZED "interrupt"
wenzelm@28197
   314
  (fn () => TaskQueue.interrupt_external (! queue) id);
wenzelm@28191
   315
wenzelm@28206
   316
(*cancel: present and future group members will be interrupted eventually*)
wenzelm@28206
   317
fun cancel x =
wenzelm@28464
   318
 (scheduler_check "cancel check";
wenzelm@28208
   319
  SYNCHRONIZED "cancel" (fn () => (change canceled (cons (group_of x)); notify_all ())));
wenzelm@28206
   320
wenzelm@28206
   321
wenzelm@28203
   322
(*global join and shutdown*)
wenzelm@28203
   323
fun shutdown () =
wenzelm@28276
   324
  if Multithreading.available then
wenzelm@28464
   325
   (scheduler_check "shutdown check";
wenzelm@28276
   326
    SYNCHRONIZED "shutdown" (fn () =>
wenzelm@28276
   327
     (while not (scheduler_active ()) do wait "shutdown: scheduler inactive";
wenzelm@28276
   328
      while not (TaskQueue.is_empty (! queue)) do wait "shutdown: join";
wenzelm@28276
   329
      do_shutdown := true;
wenzelm@28276
   330
      notify_all ();
wenzelm@28276
   331
      while not (null (! workers)) do wait "shutdown: workers";
wenzelm@28470
   332
      while scheduler_active () do wait "shutdown: scheduler still active";
wenzelm@28470
   333
      OS.Process.sleep (Time.fromMilliseconds 300))))
wenzelm@28276
   334
  else ();
wenzelm@28203
   335
wenzelm@28156
   336
end;
wenzelm@28972
   337
wenzelm@28972
   338
type 'a future = 'a Future.future;
wenzelm@28972
   339