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