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