src/Pure/Concurrent/future.ML
author wenzelm
Thu, 09 Oct 2008 20:53:13 +0200
changeset 28546 d57bfb44c9e5
parent 28534 4c7704c08951
child 28548 003f52c2bb8f
permissions -rw-r--r--
Dummy version of parallel list combinators -- plain sequential evaluation.
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
     1
(*  Title:      Pure/Concurrent/future.ML
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
     2
    ID:         $Id$
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
     3
    Author:     Makarius
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
     4
28201
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
     5
Future values.
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
     6
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
     7
Notes:
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
     8
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
     9
  * Futures are similar to delayed evaluation, i.e. delay/force is
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    10
    generalized to fork/join (and variants).  The idea is to model
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    11
    parallel value-oriented computations, but *not* communicating
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    12
    processes.
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    13
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    14
  * Futures are grouped; failure of one group member causes the whole
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    15
    group to be interrupted eventually.
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    16
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    17
  * Forked futures are evaluated spontaneously by a farm of worker
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    18
    threads in the background; join resynchronizes the computation and
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    19
    delivers results (values or exceptions).
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    20
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    21
  * The pool of worker threads is limited, usually in correlation with
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    22
    the number of physical cores on the machine.  Note that allocation
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    23
    of runtime resources is distorted either if workers yield CPU time
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    24
    (e.g. via system sleep or wait operations), or if non-worker
7ae5cdb7b122 some general notes on future values;
wenzelm
parents: 28197
diff changeset
    25
    threads contend for significant runtime resources independently.
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    26
*)
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    27
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    28
signature FUTURE =
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    29
sig
28166
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
    30
  type task = TaskQueue.task
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
    31
  type group = TaskQueue.group
28386
f2f1dd50da5a thread_data: include thread name, export access;
wenzelm
parents: 28382
diff changeset
    32
  val thread_data: unit -> (string * task * group) option
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    33
  type 'a T
28166
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
    34
  val task_of: 'a T -> task
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    35
  val group_of: 'a T -> group
28415
bf08f955e7db added str_of;
wenzelm
parents: 28390
diff changeset
    36
  val str_of: 'a T -> string
28320
c6aef67f964d added is_finished;
wenzelm
parents: 28304
diff changeset
    37
  val is_finished: 'a T -> bool
28304
4b0477452943 future tasks: support boolean priorities (true = high, false = low/irrelevant);
wenzelm
parents: 28276
diff changeset
    38
  val future: group option -> task list -> bool -> (unit -> 'a) -> 'a T
28166
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
    39
  val fork: (unit -> 'a) -> 'a T
28430
29b2886114fb renamed Future.fork_irrelevant to Future.fork_background;
wenzelm
parents: 28415
diff changeset
    40
  val fork_background: (unit -> 'a) -> 'a T
28193
7ed74d0ba607 replaced join_all by join_results, which returns Exn.results;
wenzelm
parents: 28192
diff changeset
    41
  val join_results: 'a T list -> 'a Exn.result list
28166
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
    42
  val join: 'a T -> 'a
28202
23cb9a974630 added focus, which indicates a particular collection of high-priority tasks;
wenzelm
parents: 28201
diff changeset
    43
  val focus: task list -> unit
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
    44
  val interrupt_task: string -> unit
28197
7053c539ecd8 added interrupt_task (external id);
wenzelm
parents: 28193
diff changeset
    45
  val cancel: 'a T -> unit
28203
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
    46
  val shutdown: unit -> unit
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    47
end;
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    48
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    49
structure Future: FUTURE =
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    50
struct
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    51
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    52
(** future values **)
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    53
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    54
(* identifiers *)
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    55
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    56
type task = TaskQueue.task;
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    57
type group = TaskQueue.group;
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    58
28386
f2f1dd50da5a thread_data: include thread name, export access;
wenzelm
parents: 28382
diff changeset
    59
local val tag = Universal.tag () : (string * task * group) option Universal.tag in
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    60
  fun thread_data () = the_default NONE (Thread.getLocal tag);
28390
0b9fb63b8e1d proper setmp_thread_data for nested execute (cf. join_loop);
wenzelm
parents: 28386
diff changeset
    61
  fun setmp_thread_data data f x = Library.setmp_thread_data tag (thread_data ()) (SOME data) f x;
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    62
end;
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    63
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    64
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    65
(* datatype future *)
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    66
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    67
datatype 'a T = Future of
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    68
 {task: task,
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    69
  group: group,
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    70
  result: 'a Exn.result option ref};
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    71
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    72
fun task_of (Future {task, ...}) = task;
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    73
fun group_of (Future {group, ...}) = group;
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    74
28415
bf08f955e7db added str_of;
wenzelm
parents: 28390
diff changeset
    75
fun str_of (Future {result, ...}) =
bf08f955e7db added str_of;
wenzelm
parents: 28390
diff changeset
    76
  (case ! result of
bf08f955e7db added str_of;
wenzelm
parents: 28390
diff changeset
    77
    NONE => "<future>"
bf08f955e7db added str_of;
wenzelm
parents: 28390
diff changeset
    78
  | SOME (Exn.Result _) => "<finished future>"
bf08f955e7db added str_of;
wenzelm
parents: 28390
diff changeset
    79
  | SOME (Exn.Exn _) => "<failed future>");
bf08f955e7db added str_of;
wenzelm
parents: 28390
diff changeset
    80
28320
c6aef67f964d added is_finished;
wenzelm
parents: 28304
diff changeset
    81
fun is_finished (Future {result, ...}) = is_some (! result);
c6aef67f964d added is_finished;
wenzelm
parents: 28304
diff changeset
    82
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
    83
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    84
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    85
(** scheduling **)
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    86
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    87
(* global state *)
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    88
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    89
val queue = ref TaskQueue.empty;
28468
7c80ab57f56d more tuning of tracing messages;
wenzelm
parents: 28464
diff changeset
    90
val next = ref 0;
28192
6d977729c8fa workers: explicit activity flag;
wenzelm
parents: 28191
diff changeset
    91
val workers = ref ([]: (Thread.thread * bool) list);
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    92
val scheduler = ref (NONE: Thread.thread option);
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    93
val excessive = ref 0;
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
    94
val canceled = ref ([]: TaskQueue.group list);
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
    95
val do_shutdown = ref false;
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    96
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    97
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
    98
(* synchronization *)
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
    99
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   100
local
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   101
  val lock = Mutex.mutex ();
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   102
  val cond = ConditionVar.conditionVar ();
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   103
in
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   104
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   105
fun SYNCHRONIZED name e = Exn.release (uninterruptible (fn restore_attributes => fn () =>
28162
55772e4e95e0 tuned check_cache;
wenzelm
parents: 28156
diff changeset
   106
  let
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   107
    val _ =
28534
4c7704c08951 less tracing;
wenzelm
parents: 28532
diff changeset
   108
      if Mutex.trylock lock then ()
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   109
      else
28534
4c7704c08951 less tracing;
wenzelm
parents: 28532
diff changeset
   110
       (Multithreading.tracing 3 (fn () => name ^ ": locking ...");
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   111
        Mutex.lock lock;
28534
4c7704c08951 less tracing;
wenzelm
parents: 28532
diff changeset
   112
        Multithreading.tracing 3 (fn () => name ^ ": ... locked"));
28162
55772e4e95e0 tuned check_cache;
wenzelm
parents: 28156
diff changeset
   113
    val result = Exn.capture (restore_attributes e) ();
55772e4e95e0 tuned check_cache;
wenzelm
parents: 28156
diff changeset
   114
    val _ = Mutex.unlock lock;
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   115
  in result end) ());
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   116
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   117
fun wait name = (*requires SYNCHRONIZED*)
28468
7c80ab57f56d more tuning of tracing messages;
wenzelm
parents: 28464
diff changeset
   118
 (Multithreading.tracing 3 (fn () => name ^ ": wait ...");
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   119
  ConditionVar.wait (cond, lock);
28468
7c80ab57f56d more tuning of tracing messages;
wenzelm
parents: 28464
diff changeset
   120
  Multithreading.tracing 3 (fn () => name ^ ": ... continue"));
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   121
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   122
fun wait_timeout name timeout = (*requires SYNCHRONIZED*)
28468
7c80ab57f56d more tuning of tracing messages;
wenzelm
parents: 28464
diff changeset
   123
 (Multithreading.tracing 3 (fn () => name ^ ": wait ...");
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   124
  ConditionVar.waitUntil (cond, lock, Time.+ (Time.now (), timeout));
28468
7c80ab57f56d more tuning of tracing messages;
wenzelm
parents: 28464
diff changeset
   125
  Multithreading.tracing 3 (fn () => name ^ ": ... continue"));
28166
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
   126
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
   127
fun notify_all () = (*requires SYNCHRONIZED*)
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
   128
  ConditionVar.broadcast cond;
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   129
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   130
end;
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   131
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   132
28382
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   133
(* worker activity *)
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   134
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   135
fun trace_active () =
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   136
  let
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   137
    val ws = ! workers;
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   138
    val m = string_of_int (length ws);
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   139
    val n = string_of_int (length (filter #2 ws));
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   140
  in Multithreading.tracing 1 (fn () => "SCHEDULE: " ^ m ^ " workers, " ^ n ^ " active") end;
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   141
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   142
fun change_active active = (*requires SYNCHRONIZED*)
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   143
  change workers (AList.update Thread.equal (Thread.self (), active));
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   144
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   145
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
   146
(* execute *)
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   147
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   148
fun execute name (task, group, run) =
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   149
  let
28382
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   150
    val _ = trace_active ();
28390
0b9fb63b8e1d proper setmp_thread_data for nested execute (cf. join_loop);
wenzelm
parents: 28386
diff changeset
   151
    val ok = setmp_thread_data (name, task, group) run ();
28192
6d977729c8fa workers: explicit activity flag;
wenzelm
parents: 28191
diff changeset
   152
    val _ = SYNCHRONIZED "execute" (fn () =>
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
   153
     (change queue (TaskQueue.finish task);
28186
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   154
      if ok then ()
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   155
      else if TaskQueue.cancel (! queue) group then ()
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   156
      else change canceled (cons group);
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
   157
      notify_all ()));
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   158
  in () end;
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   159
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   160
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   161
(* worker threads *)
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   162
28186
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   163
fun worker_wait name = (*requires SYNCHRONIZED*)
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   164
  (change_active false; wait name; change_active true);
28162
55772e4e95e0 tuned check_cache;
wenzelm
parents: 28156
diff changeset
   165
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   166
fun worker_next name = (*requires SYNCHRONIZED*)
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   167
  if ! excessive > 0 then
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   168
    (dec excessive;
28192
6d977729c8fa workers: explicit activity flag;
wenzelm
parents: 28191
diff changeset
   169
     change workers (filter_out (fn (thread, _) => Thread.equal (thread, Thread.self ())));
28203
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
   170
     notify_all ();
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   171
     NONE)
28166
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
   172
  else
28186
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   173
    (case change_result queue TaskQueue.dequeue of
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   174
      NONE => (worker_wait name; worker_next name)
28166
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
   175
    | some => some);
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   176
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   177
fun worker_loop name =
28192
6d977729c8fa workers: explicit activity flag;
wenzelm
parents: 28191
diff changeset
   178
  (case SYNCHRONIZED name (fn () => worker_next name) of
28468
7c80ab57f56d more tuning of tracing messages;
wenzelm
parents: 28464
diff changeset
   179
    NONE => Multithreading.tracing 3 (fn () => name ^ ": exit")
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   180
  | SOME work => (execute name work; worker_loop name));
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   181
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   182
fun worker_start name = (*requires SYNCHRONIZED*)
28242
f978c8e75118 SimpleThread.fork;
wenzelm
parents: 28208
diff changeset
   183
  change workers (cons (SimpleThread.fork false (fn () => worker_loop name), true));
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   184
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   185
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   186
(* scheduler *)
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   187
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   188
fun scheduler_next () = (*requires SYNCHRONIZED*)
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   189
  let
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   190
    (*worker threads*)
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   191
    val _ =
28192
6d977729c8fa workers: explicit activity flag;
wenzelm
parents: 28191
diff changeset
   192
      (case List.partition (Thread.isActive o #1) (! workers) of
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   193
        (_, []) => ()
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   194
      | (active, inactive) =>
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   195
          (workers := active; Multithreading.tracing 0 (fn () =>
28192
6d977729c8fa workers: explicit activity flag;
wenzelm
parents: 28191
diff changeset
   196
            "SCHEDULE: disposed " ^ string_of_int (length inactive) ^ " dead worker threads")));
28382
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   197
    val _ = trace_active ();
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   198
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   199
    val m = if ! do_shutdown then 0 else Multithreading.max_threads_value ();
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   200
    val l = length (! workers);
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   201
    val _ = excessive := l - m;
28203
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
   202
    val _ =
28468
7c80ab57f56d more tuning of tracing messages;
wenzelm
parents: 28464
diff changeset
   203
      if m > l then funpow (m - l) (fn () => worker_start ("worker " ^ string_of_int (inc next))) ()
28203
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
   204
      else ();
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   205
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   206
    (*canceled groups*)
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   207
    val _ =  change canceled (filter_out (TaskQueue.cancel (! queue)));
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   208
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   209
    (*shutdown*)
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   210
    val continue = not (! do_shutdown andalso null (! workers));
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   211
    val _ = if continue then () else scheduler := NONE;
28167
27e2ca41b58c more interrupt operations;
wenzelm
parents: 28166
diff changeset
   212
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   213
    val _ = notify_all ();
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   214
    val _ = wait_timeout "scheduler" (Time.fromSeconds 3);
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   215
  in continue end;
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   216
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   217
fun scheduler_loop () =
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   218
 (while SYNCHRONIZED "scheduler" scheduler_next do ();
28534
4c7704c08951 less tracing;
wenzelm
parents: 28532
diff changeset
   219
  Multithreading.tracing 3 (fn () => "scheduler: exit"));
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   220
28203
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
   221
fun scheduler_active () = (*requires SYNCHRONIZED*)
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
   222
  (case ! scheduler of NONE => false | SOME thread => Thread.isActive thread);
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
   223
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   224
fun scheduler_check name = SYNCHRONIZED name (fn () =>
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   225
  if not (scheduler_active ()) then
28534
4c7704c08951 less tracing;
wenzelm
parents: 28532
diff changeset
   226
    (Multithreading.tracing 3 (fn () => "scheduler: fork");
4c7704c08951 less tracing;
wenzelm
parents: 28532
diff changeset
   227
     do_shutdown := false; scheduler := SOME (SimpleThread.fork false scheduler_loop))
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   228
  else if ! do_shutdown then error "Scheduler shutdown in progress"
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   229
  else ());
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   230
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   231
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   232
(* future values: fork independent computation *)
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   233
28304
4b0477452943 future tasks: support boolean priorities (true = high, false = low/irrelevant);
wenzelm
parents: 28276
diff changeset
   234
fun future opt_group deps pri (e: unit -> 'a) =
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   235
  let
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   236
    val _ = scheduler_check "future check";
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
   237
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   238
    val group = (case opt_group of SOME group => group | NONE => TaskQueue.new_group ());
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
   239
28166
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
   240
    val result = ref (NONE: 'a Exn.result option);
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
   241
    val run = Multithreading.with_attributes (Thread.getAttributes ())
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
   242
      (fn _ => fn ok =>
28532
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   243
        let
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   244
          val res = if ok then Exn.capture e () else Exn.Exn Exn.Interrupt;
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   245
          val res_ok =
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   246
            (case res of
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   247
              Exn.Result _ => true
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   248
            | Exn.Exn Exn.Interrupt => true
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   249
            | _ => false);
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   250
        in result := SOME res; res_ok end);
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
   251
28192
6d977729c8fa workers: explicit activity flag;
wenzelm
parents: 28191
diff changeset
   252
    val task = SYNCHRONIZED "future" (fn () =>
28304
4b0477452943 future tasks: support boolean priorities (true = high, false = low/irrelevant);
wenzelm
parents: 28276
diff changeset
   253
      change_result queue (TaskQueue.enqueue group deps pri run) before notify_all ());
28166
43087721a66e moved task, thread_data, group, queue to task_queue.ML;
wenzelm
parents: 28163
diff changeset
   254
  in Future {task = task, group = group, result = result} end;
28162
55772e4e95e0 tuned check_cache;
wenzelm
parents: 28156
diff changeset
   255
28430
29b2886114fb renamed Future.fork_irrelevant to Future.fork_background;
wenzelm
parents: 28415
diff changeset
   256
fun fork_common pri = future (Option.map #3 (thread_data ())) [] pri;
29b2886114fb renamed Future.fork_irrelevant to Future.fork_background;
wenzelm
parents: 28415
diff changeset
   257
29b2886114fb renamed Future.fork_irrelevant to Future.fork_background;
wenzelm
parents: 28415
diff changeset
   258
fun fork e = fork_common true e;
29b2886114fb renamed Future.fork_irrelevant to Future.fork_background;
wenzelm
parents: 28415
diff changeset
   259
fun fork_background e = fork_common false e;
28186
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   260
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   261
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   262
(* join: retrieve results *)
28186
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   263
28331
33d58fdc177d join_results: special case for empty list, works without multithreading;
wenzelm
parents: 28320
diff changeset
   264
fun join_results [] = []
28532
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   265
  | join_results xs = uninterruptible (fn _ => fn () =>
28331
33d58fdc177d join_results: special case for empty list, works without multithreading;
wenzelm
parents: 28320
diff changeset
   266
      let
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   267
        val _ = scheduler_check "join check";
28331
33d58fdc177d join_results: special case for empty list, works without multithreading;
wenzelm
parents: 28320
diff changeset
   268
        val _ = Multithreading.self_critical () andalso
33d58fdc177d join_results: special case for empty list, works without multithreading;
wenzelm
parents: 28320
diff changeset
   269
          error "Cannot join future values within critical section";
28177
8c0335bc9336 inherit group from running thread, or create a new one -- make it harder to re-use canceled groups;
wenzelm
parents: 28170
diff changeset
   270
28386
f2f1dd50da5a thread_data: include thread name, export access;
wenzelm
parents: 28382
diff changeset
   271
        fun join_loop _ [] = ()
f2f1dd50da5a thread_data: include thread name, export access;
wenzelm
parents: 28382
diff changeset
   272
          | join_loop name tasks =
f2f1dd50da5a thread_data: include thread name, export access;
wenzelm
parents: 28382
diff changeset
   273
              (case SYNCHRONIZED name (fn () =>
28382
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   274
                  change_result queue (TaskQueue.dequeue_towards tasks)) of
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   275
                NONE => ()
28386
f2f1dd50da5a thread_data: include thread name, export access;
wenzelm
parents: 28382
diff changeset
   276
              | SOME (work, tasks') => (execute name work; join_loop name tasks'));
28331
33d58fdc177d join_results: special case for empty list, works without multithreading;
wenzelm
parents: 28320
diff changeset
   277
        val _ =
33d58fdc177d join_results: special case for empty list, works without multithreading;
wenzelm
parents: 28320
diff changeset
   278
          (case thread_data () of
28382
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   279
            NONE =>
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   280
              (*alien thread -- refrain from contending for resources*)
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   281
              while exists (not o is_finished) xs
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   282
              do SYNCHRONIZED "join_thread" (fn () => wait "join_thread")
28386
f2f1dd50da5a thread_data: include thread name, export access;
wenzelm
parents: 28382
diff changeset
   283
          | SOME (name, task, _) =>
28382
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   284
              (*proper task -- actively work towards results*)
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   285
              let
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   286
                val unfinished = xs |> map_filter
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   287
                  (fn Future {task, result = ref NONE, ...} => SOME task | _ => NONE);
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   288
                val _ = SYNCHRONIZED "join" (fn () =>
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   289
                  (change queue (TaskQueue.depend unfinished task); notify_all ()));
28386
f2f1dd50da5a thread_data: include thread name, export access;
wenzelm
parents: 28382
diff changeset
   290
                val _ = join_loop ("join_loop: " ^ name) unfinished;
28382
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   291
                val _ =
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   292
                  while exists (not o is_finished) xs
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   293
                  do SYNCHRONIZED "join_task" (fn () => worker_wait "join_task");
a97fa342540d added release_results (formerly in par_list.ML);
wenzelm
parents: 28380
diff changeset
   294
              in () end);
28186
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   295
28532
16c6ae7d1aa6 more careful handling of group interrupts;
wenzelm
parents: 28472
diff changeset
   296
      in xs |> map (fn Future {result = ref (SOME res), ...} => res) end) ();
28186
6a8417f36837 cancel: check_scheduler;
wenzelm
parents: 28177
diff changeset
   297
28193
7ed74d0ba607 replaced join_all by join_results, which returns Exn.results;
wenzelm
parents: 28192
diff changeset
   298
fun join x = Exn.release (singleton join_results x);
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   299
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   300
28202
23cb9a974630 added focus, which indicates a particular collection of high-priority tasks;
wenzelm
parents: 28201
diff changeset
   301
(* misc operations *)
23cb9a974630 added focus, which indicates a particular collection of high-priority tasks;
wenzelm
parents: 28201
diff changeset
   302
23cb9a974630 added focus, which indicates a particular collection of high-priority tasks;
wenzelm
parents: 28201
diff changeset
   303
(*focus: collection of high-priority task*)
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   304
fun focus tasks = SYNCHRONIZED "focus" (fn () =>
28202
23cb9a974630 added focus, which indicates a particular collection of high-priority tasks;
wenzelm
parents: 28201
diff changeset
   305
  change queue (TaskQueue.focus tasks));
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   306
28202
23cb9a974630 added focus, which indicates a particular collection of high-priority tasks;
wenzelm
parents: 28201
diff changeset
   307
(*interrupt: permissive signal, may get ignored*)
28197
7053c539ecd8 added interrupt_task (external id);
wenzelm
parents: 28193
diff changeset
   308
fun interrupt_task id = SYNCHRONIZED "interrupt"
7053c539ecd8 added interrupt_task (external id);
wenzelm
parents: 28193
diff changeset
   309
  (fn () => TaskQueue.interrupt_external (! queue) id);
28191
9e5f556409c6 future: allow explicit group;
wenzelm
parents: 28186
diff changeset
   310
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   311
(*cancel: present and future group members will be interrupted eventually*)
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   312
fun cancel x =
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   313
 (scheduler_check "cancel check";
28208
3a8b3453129a cancel, shutdown: notify_all;
wenzelm
parents: 28206
diff changeset
   314
  SYNCHRONIZED "cancel" (fn () => (change canceled (cons (group_of x)); notify_all ())));
28206
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   315
bcd48c6897d4 eliminated requests, use global state variables uniformly;
wenzelm
parents: 28203
diff changeset
   316
28203
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
   317
(*global join and shutdown*)
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
   318
fun shutdown () =
28276
fbc707811203 shutdown only if Multithreading.available;
wenzelm
parents: 28242
diff changeset
   319
  if Multithreading.available then
28464
dcc030b52583 tuned SYNCHRONIZED: outermost Exn.release;
wenzelm
parents: 28442
diff changeset
   320
   (scheduler_check "shutdown check";
28276
fbc707811203 shutdown only if Multithreading.available;
wenzelm
parents: 28242
diff changeset
   321
    SYNCHRONIZED "shutdown" (fn () =>
fbc707811203 shutdown only if Multithreading.available;
wenzelm
parents: 28242
diff changeset
   322
     (while not (scheduler_active ()) do wait "shutdown: scheduler inactive";
fbc707811203 shutdown only if Multithreading.available;
wenzelm
parents: 28242
diff changeset
   323
      while not (TaskQueue.is_empty (! queue)) do wait "shutdown: join";
fbc707811203 shutdown only if Multithreading.available;
wenzelm
parents: 28242
diff changeset
   324
      do_shutdown := true;
fbc707811203 shutdown only if Multithreading.available;
wenzelm
parents: 28242
diff changeset
   325
      notify_all ();
fbc707811203 shutdown only if Multithreading.available;
wenzelm
parents: 28242
diff changeset
   326
      while not (null (! workers)) do wait "shutdown: workers";
28470
409fedeece30 added simple heartbeat thread;
wenzelm
parents: 28468
diff changeset
   327
      while scheduler_active () do wait "shutdown: scheduler still active";
409fedeece30 added simple heartbeat thread;
wenzelm
parents: 28468
diff changeset
   328
      OS.Process.sleep (Time.fromMilliseconds 300))))
28276
fbc707811203 shutdown only if Multithreading.available;
wenzelm
parents: 28242
diff changeset
   329
  else ();
28203
88f18387f1c9 shutdown: global join-and-shutdown operation;
wenzelm
parents: 28202
diff changeset
   330
28156
5205f7979b4f Functional threads as future values.
wenzelm
parents:
diff changeset
   331
end;