src/Pure/Concurrent/future.ML
author wenzelm
Fri Mar 20 20:20:09 2009 +0100 (2009-03-20 ago)
changeset 30612 cb6421b6a18f
parent 29551 95e469919c3e
child 30618 046f4f986fb5
permissions -rw-r--r--
future_job: do not inherit attributes, but enforce restricted interrupts -- attempt to prevent interrupt race conditions;
wenzelm@28156
     1
(*  Title:      Pure/Concurrent/future.ML
wenzelm@28156
     2
    Author:     Makarius
wenzelm@28156
     3
wenzelm@28201
     4
Future values.
wenzelm@28201
     5
wenzelm@28201
     6
Notes:
wenzelm@28201
     7
wenzelm@28201
     8
  * Futures are similar to delayed evaluation, i.e. delay/force is
wenzelm@28201
     9
    generalized to fork/join (and variants).  The idea is to model
wenzelm@28201
    10
    parallel value-oriented computations, but *not* communicating
wenzelm@28201
    11
    processes.
wenzelm@28201
    12
wenzelm@28201
    13
  * Futures are grouped; failure of one group member causes the whole
wenzelm@28201
    14
    group to be interrupted eventually.
wenzelm@28201
    15
wenzelm@28201
    16
  * Forked futures are evaluated spontaneously by a farm of worker
wenzelm@28201
    17
    threads in the background; join resynchronizes the computation and
wenzelm@28201
    18
    delivers results (values or exceptions).
wenzelm@28201
    19
wenzelm@28201
    20
  * The pool of worker threads is limited, usually in correlation with
wenzelm@28201
    21
    the number of physical cores on the machine.  Note that allocation
wenzelm@28201
    22
    of runtime resources is distorted either if workers yield CPU time
wenzelm@28201
    23
    (e.g. via system sleep or wait operations), or if non-worker
wenzelm@28201
    24
    threads contend for significant runtime resources independently.
wenzelm@28156
    25
*)
wenzelm@28156
    26
wenzelm@28156
    27
signature FUTURE =
wenzelm@28156
    28
sig
wenzelm@28645
    29
  val enabled: unit -> bool
wenzelm@29119
    30
  type task = Task_Queue.task
wenzelm@29119
    31
  type group = Task_Queue.group
wenzelm@28979
    32
  val thread_data: unit -> (string * task) option
wenzelm@28972
    33
  type 'a future
wenzelm@28972
    34
  val task_of: 'a future -> task
wenzelm@28972
    35
  val group_of: 'a future -> group
wenzelm@28972
    36
  val peek: 'a future -> 'a Exn.result option
wenzelm@28972
    37
  val is_finished: 'a future -> bool
wenzelm@28997
    38
  val value: 'a -> 'a future
wenzelm@28972
    39
  val fork: (unit -> 'a) -> 'a future
wenzelm@28979
    40
  val fork_group: group -> (unit -> 'a) -> 'a future
wenzelm@28979
    41
  val fork_deps: 'b future list -> (unit -> 'a) -> 'a future
wenzelm@29119
    42
  val fork_pri: int -> (unit -> 'a) -> 'a future
wenzelm@28972
    43
  val join_results: 'a future list -> 'a Exn.result list
wenzelm@28972
    44
  val join_result: 'a future -> 'a Exn.result
wenzelm@28972
    45
  val join: 'a future -> 'a
wenzelm@28972
    46
  val map: ('a -> 'b) -> 'a future -> 'b future
wenzelm@28206
    47
  val interrupt_task: string -> unit
wenzelm@29431
    48
  val cancel_group: group -> unit
wenzelm@28972
    49
  val cancel: 'a future -> unit
wenzelm@28203
    50
  val shutdown: unit -> unit
wenzelm@28156
    51
end;
wenzelm@28156
    52
wenzelm@28156
    53
structure Future: FUTURE =
wenzelm@28156
    54
struct
wenzelm@28156
    55
wenzelm@28177
    56
(** future values **)
wenzelm@28177
    57
wenzelm@28645
    58
fun enabled () =
wenzelm@29118
    59
  Multithreading.enabled () andalso
wenzelm@28645
    60
    not (Multithreading.self_critical ());
wenzelm@28645
    61
wenzelm@28645
    62
wenzelm@28167
    63
(* identifiers *)
wenzelm@28167
    64
wenzelm@29119
    65
type task = Task_Queue.task;
wenzelm@29119
    66
type group = Task_Queue.group;
wenzelm@28167
    67
wenzelm@28979
    68
local val tag = Universal.tag () : (string * task) option Universal.tag in
wenzelm@28177
    69
  fun thread_data () = the_default NONE (Thread.getLocal tag);
wenzelm@28390
    70
  fun setmp_thread_data data f x = Library.setmp_thread_data tag (thread_data ()) (SOME data) f x;
wenzelm@28167
    71
end;
wenzelm@28167
    72
wenzelm@28167
    73
wenzelm@28167
    74
(* datatype future *)
wenzelm@28167
    75
wenzelm@28972
    76
datatype 'a future = Future of
wenzelm@28167
    77
 {task: task,
wenzelm@28177
    78
  group: group,
wenzelm@28167
    79
  result: 'a Exn.result option ref};
wenzelm@28167
    80
wenzelm@28167
    81
fun task_of (Future {task, ...}) = task;
wenzelm@28167
    82
fun group_of (Future {group, ...}) = group;
wenzelm@28167
    83
wenzelm@28558
    84
fun peek (Future {result, ...}) = ! result;
wenzelm@28558
    85
fun is_finished x = is_some (peek x);
wenzelm@28320
    86
wenzelm@28997
    87
fun value x = Future
wenzelm@29119
    88
 {task = Task_Queue.new_task 0,
wenzelm@29119
    89
  group = Task_Queue.new_group (),
wenzelm@28997
    90
  result = ref (SOME (Exn.Result x))};
wenzelm@28997
    91
wenzelm@28167
    92
wenzelm@28177
    93
wenzelm@28177
    94
(** scheduling **)
wenzelm@28177
    95
wenzelm@28177
    96
(* global state *)
wenzelm@28177
    97
wenzelm@29119
    98
val queue = ref Task_Queue.empty;
wenzelm@28468
    99
val next = ref 0;
wenzelm@28192
   100
val workers = ref ([]: (Thread.thread * bool) list);
wenzelm@28177
   101
val scheduler = ref (NONE: Thread.thread option);
wenzelm@28177
   102
val excessive = ref 0;
wenzelm@29119
   103
val canceled = ref ([]: Task_Queue.group list);
wenzelm@28206
   104
val do_shutdown = ref false;
wenzelm@28177
   105
wenzelm@28177
   106
wenzelm@28177
   107
(* synchronization *)
wenzelm@28156
   108
wenzelm@28156
   109
local
wenzelm@28156
   110
  val lock = Mutex.mutex ();
wenzelm@28156
   111
  val cond = ConditionVar.conditionVar ();
wenzelm@28156
   112
in
wenzelm@28156
   113
wenzelm@28575
   114
fun SYNCHRONIZED name = SimpleThread.synchronized name lock;
wenzelm@28156
   115
wenzelm@29119
   116
fun wait () = (*requires SYNCHRONIZED*)
wenzelm@28206
   117
  ConditionVar.wait (cond, lock);
wenzelm@28206
   118
wenzelm@29119
   119
fun wait_timeout timeout = (*requires SYNCHRONIZED*)
wenzelm@29341
   120
  ignore (ConditionVar.waitUntil (cond, lock, Time.+ (Time.now (), timeout)));
wenzelm@28166
   121
wenzelm@28166
   122
fun notify_all () = (*requires SYNCHRONIZED*)
wenzelm@28166
   123
  ConditionVar.broadcast cond;
wenzelm@28156
   124
wenzelm@28156
   125
end;
wenzelm@28156
   126
wenzelm@28156
   127
wenzelm@28382
   128
(* worker activity *)
wenzelm@28382
   129
wenzelm@28382
   130
fun trace_active () =
wenzelm@28382
   131
  let
wenzelm@28382
   132
    val ws = ! workers;
wenzelm@28382
   133
    val m = string_of_int (length ws);
wenzelm@28382
   134
    val n = string_of_int (length (filter #2 ws));
wenzelm@28382
   135
  in Multithreading.tracing 1 (fn () => "SCHEDULE: " ^ m ^ " workers, " ^ n ^ " active") end;
wenzelm@28382
   136
wenzelm@28382
   137
fun change_active active = (*requires SYNCHRONIZED*)
wenzelm@28382
   138
  change workers (AList.update Thread.equal (Thread.self (), active));
wenzelm@28382
   139
wenzelm@28382
   140
wenzelm@29366
   141
(* execute jobs *)
wenzelm@28156
   142
wenzelm@29341
   143
fun do_cancel group = (*requires SYNCHRONIZED*)
wenzelm@29341
   144
  change canceled (insert Task_Queue.eq_group group);
wenzelm@29341
   145
wenzelm@29366
   146
fun execute name (task, group, jobs) =
wenzelm@28167
   147
  let
wenzelm@28382
   148
    val _ = trace_active ();
wenzelm@29384
   149
    val valid = Task_Queue.is_valid group;
wenzelm@29366
   150
    val ok = setmp_thread_data (name, task) (fn () =>
wenzelm@29384
   151
      fold (fn job => fn ok => job valid andalso ok) jobs true) ();
wenzelm@28192
   152
    val _ = SYNCHRONIZED "execute" (fn () =>
wenzelm@29119
   153
     (change queue (Task_Queue.finish task);
wenzelm@28186
   154
      if ok then ()
wenzelm@29119
   155
      else if Task_Queue.cancel (! queue) group then ()
wenzelm@29341
   156
      else do_cancel 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@29119
   163
fun worker_wait () = (*requires SYNCHRONIZED*)
wenzelm@29119
   164
  (change_active false; wait (); change_active true);
wenzelm@28162
   165
wenzelm@29119
   166
fun worker_next () = (*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@29119
   173
    (case change_result queue Task_Queue.dequeue of
wenzelm@29119
   174
      NONE => (worker_wait (); worker_next ())
wenzelm@28166
   175
    | some => some);
wenzelm@28156
   176
wenzelm@28167
   177
fun worker_loop name =
wenzelm@29119
   178
  (case SYNCHRONIZED name worker_next of
wenzelm@29119
   179
    NONE => ()
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@29119
   207
    val _ =  change canceled (filter_out (Task_Queue.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@29341
   214
    val _ = interruptible (fn () => wait_timeout (Time.fromSeconds 1)) ()
wenzelm@29341
   215
      handle Exn.Interrupt => List.app do_cancel (Task_Queue.cancel_all (! queue));
wenzelm@28206
   216
  in continue end;
wenzelm@28206
   217
wenzelm@28206
   218
fun scheduler_loop () =
wenzelm@29119
   219
  while SYNCHRONIZED "scheduler" scheduler_next do ();
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@29119
   226
    (do_shutdown := false; scheduler := SOME (SimpleThread.fork false scheduler_loop))
wenzelm@28206
   227
  else if ! do_shutdown then error "Scheduler shutdown in progress"
wenzelm@28206
   228
  else ());
wenzelm@28156
   229
wenzelm@28156
   230
wenzelm@29366
   231
wenzelm@29366
   232
(** futures **)
wenzelm@28156
   233
wenzelm@29366
   234
(* future job: fill result *)
wenzelm@29366
   235
wenzelm@29366
   236
fun future_job group (e: unit -> 'a) =
wenzelm@28156
   237
  let
wenzelm@28166
   238
    val result = ref (NONE: 'a Exn.result option);
wenzelm@30612
   239
    val job = Multithreading.with_attributes Multithreading.restricted_interrupts
wenzelm@28177
   240
      (fn _ => fn ok =>
wenzelm@28532
   241
        let
wenzelm@28532
   242
          val res = if ok then Exn.capture e () else Exn.Exn Exn.Interrupt;
wenzelm@28548
   243
          val _ = result := SOME res;
wenzelm@28532
   244
          val res_ok =
wenzelm@28532
   245
            (case res of
wenzelm@28532
   246
              Exn.Result _ => true
wenzelm@29119
   247
            | Exn.Exn Exn.Interrupt => (Task_Queue.invalidate_group group; true)
wenzelm@28532
   248
            | _ => false);
wenzelm@28548
   249
        in res_ok end);
wenzelm@29366
   250
  in (result, job) end;
wenzelm@28177
   251
wenzelm@29366
   252
wenzelm@29366
   253
(* fork *)
wenzelm@29366
   254
wenzelm@29366
   255
fun fork_future opt_group deps pri e =
wenzelm@29366
   256
  let
wenzelm@29366
   257
    val _ = scheduler_check "future check";
wenzelm@29366
   258
wenzelm@29366
   259
    val group = (case opt_group of SOME group => group | NONE => Task_Queue.new_group ());
wenzelm@29366
   260
    val (result, job) = future_job group e;
wenzelm@28192
   261
    val task = SYNCHRONIZED "future" (fn () =>
wenzelm@29366
   262
      change_result queue (Task_Queue.enqueue group deps pri job) before notify_all ());
wenzelm@28166
   263
  in Future {task = task, group = group, result = result} end;
wenzelm@28162
   264
wenzelm@29366
   265
fun fork e = fork_future NONE [] 0 e;
wenzelm@29366
   266
fun fork_group group e = fork_future (SOME group) [] 0 e;
wenzelm@29366
   267
fun fork_deps deps e = fork_future NONE (map task_of deps) 0 e;
wenzelm@29366
   268
fun fork_pri pri e = fork_future NONE [] pri e;
wenzelm@28186
   269
wenzelm@28186
   270
wenzelm@29366
   271
(* join *)
wenzelm@29366
   272
wenzelm@29551
   273
local
wenzelm@29551
   274
wenzelm@29366
   275
fun get_result x = the_default (Exn.Exn (SYS_ERROR "unfinished future")) (peek x);
wenzelm@28186
   276
wenzelm@29551
   277
fun join_next pending = (*requires SYNCHRONIZED*)
wenzelm@29551
   278
  if forall is_finished pending then NONE
wenzelm@29551
   279
  else
wenzelm@29551
   280
    (case change_result queue Task_Queue.dequeue of
wenzelm@29551
   281
      NONE => (worker_wait (); join_next pending)
wenzelm@29551
   282
    | some => some);
wenzelm@29551
   283
wenzelm@29551
   284
fun join_loop name pending =
wenzelm@29551
   285
  (case SYNCHRONIZED name (fn () => join_next pending) of
wenzelm@29551
   286
    NONE => ()
wenzelm@29551
   287
  | SOME work => (execute name work; join_loop name pending));
wenzelm@29551
   288
wenzelm@29551
   289
in
wenzelm@29551
   290
wenzelm@29366
   291
fun join_results xs =
wenzelm@29366
   292
  if forall is_finished xs then map get_result xs
wenzelm@29366
   293
  else uninterruptible (fn _ => fn () =>
wenzelm@29366
   294
    let
wenzelm@29366
   295
      val _ = scheduler_check "join check";
wenzelm@29366
   296
      val _ = Multithreading.self_critical () andalso
wenzelm@29366
   297
        error "Cannot join future values within critical section";
wenzelm@28177
   298
wenzelm@29551
   299
      fun join_deps _ [] = ()
wenzelm@29551
   300
        | join_deps name deps =
wenzelm@29366
   301
            (case SYNCHRONIZED name (fn () =>
wenzelm@29366
   302
                change_result queue (Task_Queue.dequeue_towards deps)) of
wenzelm@29366
   303
              NONE => ()
wenzelm@29551
   304
            | SOME (work, deps') => (execute name work; join_deps name deps'));
wenzelm@29551
   305
wenzelm@29366
   306
      val _ =
wenzelm@29366
   307
        (case thread_data () of
wenzelm@29366
   308
          NONE =>
wenzelm@29366
   309
            (*alien thread -- refrain from contending for resources*)
wenzelm@29366
   310
            while not (forall is_finished xs)
wenzelm@29366
   311
            do SYNCHRONIZED "join_thread" (fn () => wait ())
wenzelm@29366
   312
        | SOME (name, task) =>
wenzelm@29366
   313
            (*proper task -- actively work towards results*)
wenzelm@29366
   314
            let
wenzelm@29366
   315
              val pending = filter_out is_finished xs;
wenzelm@29366
   316
              val deps = map task_of pending;
wenzelm@29366
   317
              val _ = SYNCHRONIZED "join" (fn () =>
wenzelm@29366
   318
                (change queue (Task_Queue.depend deps task); notify_all ()));
wenzelm@29551
   319
              val _ = join_deps ("join_deps: " ^ name) deps;
wenzelm@29551
   320
              val _ = join_loop ("join_loop: " ^ name) (filter_out is_finished pending);
wenzelm@29366
   321
            in () end);
wenzelm@28186
   322
wenzelm@29366
   323
    in map get_result xs end) ();
wenzelm@28186
   324
wenzelm@29551
   325
end;
wenzelm@29551
   326
wenzelm@28647
   327
fun join_result x = singleton join_results x;
wenzelm@28647
   328
fun join x = Exn.release (join_result x);
wenzelm@28156
   329
wenzelm@29366
   330
wenzelm@29366
   331
(* map *)
wenzelm@29366
   332
wenzelm@29384
   333
fun map_future f x =
wenzelm@29366
   334
  let
wenzelm@29366
   335
    val _ = scheduler_check "map_future check";
wenzelm@29366
   336
wenzelm@29384
   337
    val task = task_of x;
wenzelm@29384
   338
    val group = Task_Queue.new_group ();
wenzelm@29384
   339
    val (result, job) = future_job group (fn () => f (join x));
wenzelm@29384
   340
wenzelm@29366
   341
    val extended = SYNCHRONIZED "map_future" (fn () =>
wenzelm@29366
   342
      (case Task_Queue.extend task job (! queue) of
wenzelm@29366
   343
        SOME queue' => (queue := queue'; true)
wenzelm@29366
   344
      | NONE => false));
wenzelm@29366
   345
  in
wenzelm@29384
   346
    if extended then Future {task = task, group = group, result = result}
wenzelm@29384
   347
    else fork_future NONE [task] (Task_Queue.pri_of_task task) (fn () => f (join x))
wenzelm@29366
   348
  end;
wenzelm@28979
   349
wenzelm@28191
   350
wenzelm@29431
   351
(* cancellation *)
wenzelm@28202
   352
wenzelm@28202
   353
(*interrupt: permissive signal, may get ignored*)
wenzelm@28197
   354
fun interrupt_task id = SYNCHRONIZED "interrupt"
wenzelm@29119
   355
  (fn () => Task_Queue.interrupt_external (! queue) id);
wenzelm@28191
   356
wenzelm@28206
   357
(*cancel: present and future group members will be interrupted eventually*)
wenzelm@29431
   358
fun cancel_group group =
wenzelm@28464
   359
 (scheduler_check "cancel check";
wenzelm@29431
   360
  SYNCHRONIZED "cancel" (fn () => (do_cancel group; notify_all ())));
wenzelm@28206
   361
wenzelm@29431
   362
fun cancel x = cancel_group (group_of x);
wenzelm@28206
   363
wenzelm@29366
   364
wenzelm@29366
   365
(** global join and shutdown **)
wenzelm@29366
   366
wenzelm@28203
   367
fun shutdown () =
wenzelm@28276
   368
  if Multithreading.available then
wenzelm@28464
   369
   (scheduler_check "shutdown check";
wenzelm@28276
   370
    SYNCHRONIZED "shutdown" (fn () =>
wenzelm@29119
   371
     (while not (scheduler_active ()) do wait ();
wenzelm@29119
   372
      while not (Task_Queue.is_empty (! queue)) do wait ();
wenzelm@28276
   373
      do_shutdown := true;
wenzelm@28276
   374
      notify_all ();
wenzelm@29119
   375
      while not (null (! workers)) do wait ();
wenzelm@29119
   376
      while scheduler_active () do wait ();
wenzelm@28470
   377
      OS.Process.sleep (Time.fromMilliseconds 300))))
wenzelm@28276
   378
  else ();
wenzelm@28203
   379
wenzelm@29366
   380
wenzelm@29366
   381
(*final declarations of this structure!*)
wenzelm@29366
   382
val map = map_future;
wenzelm@29366
   383
wenzelm@28156
   384
end;
wenzelm@28972
   385
wenzelm@28972
   386
type 'a future = 'a Future.future;
wenzelm@28972
   387