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