/
task.ex
1337 lines (1046 loc) · 45.8 KB
/
task.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Task do
@moduledoc """
Conveniences for spawning and awaiting tasks.
Tasks are processes meant to execute one particular
action throughout their lifetime, often with little or no
communication with other processes. The most common use case
for tasks is to convert sequential code into concurrent code
by computing a value asynchronously:
task = Task.async(fn -> do_some_work() end)
res = do_some_other_work()
res + Task.await(task)
Tasks spawned with `async` can be awaited on by their caller
process (and only their caller) as shown in the example above.
They are implemented by spawning a process that sends a message
to the caller once the given computation is performed.
Besides `async/1` and `await/2`, tasks can also be
started as part of a supervision tree and dynamically spawned
on remote nodes. We will explore these scenarios next.
## async and await
One of the common uses of tasks is to convert sequential code
into concurrent code with `Task.async/1` while keeping its semantics.
When invoked, a new process will be created, linked and monitored
by the caller. Once the task action finishes, a message will be sent
to the caller with the result.
`Task.await/2` is used to read the message sent by the task.
There are two important things to consider when using `async`:
1. If you are using async tasks, you **must await** a reply
as they are *always* sent. If you are not expecting a reply,
consider using `Task.start_link/1` as detailed below.
2. async tasks link the caller and the spawned process. This
means that, if the caller crashes, the task will crash
too and vice-versa. This is on purpose: if the process
meant to receive the result no longer exists, there is
no purpose in completing the computation.
If this is not desired, you will want to use supervised
tasks, described next.
## Dynamically supervised tasks
The `Task.Supervisor` module allows developers to dynamically
create multiple supervised tasks.
A short example is:
{:ok, pid} = Task.Supervisor.start_link()
task =
Task.Supervisor.async(pid, fn ->
# Do something
end)
Task.await(task)
However, in the majority of cases, you want to add the task supervisor
to your supervision tree:
Supervisor.start_link([
{Task.Supervisor, name: MyApp.TaskSupervisor}
], strategy: :one_for_one)
And now you can use async/await by passing the name of
the supervisor instead of the pid:
Task.Supervisor.async(MyApp.TaskSupervisor, fn ->
# Do something
end)
|> Task.await()
We encourage developers to rely on supervised tasks as much as possible.
Supervised tasks improves the visibility of how many tasks are running
at a given moment and enable a huge variety of patterns that gives you
explicit control on how to handle the results, errors, and timeouts.
Here is a summary:
* Using `Task.Supervisor.start_child/2` allows you to start a fire-and-forget
task that you don't care about its results or if it completes successfully or not.
* Using `Task.Supervisor.async/2` + `Task.await/2` allows you to execute
tasks concurrently and retrieve its result. If the task fails,
the caller will also fail.
* Using `Task.Supervisor.async_nolink/2` + `Task.yield/2` + `Task.shutdown/2`
allows you to execute tasks concurrently and retrieve their results
or the reason they failed within a given time frame. If the task fails,
the caller won't fail. You will receive the error reason either on
`yield` or `shutdown`.
Furthermore, the supervisor guarantee all tasks first terminate, within a
configurable shutdown period, when your application shuts down. See the
`Task.Supervisor` module for details on the supported operations.
### Distributed tasks
With `Task.Supervisor`, it is easy to dynamically start tasks across nodes:
# On the remote node named :remote@local
Task.Supervisor.start_link(name: MyApp.DistSupervisor)
# On the client
supervisor = {MyApp.DistSupervisor, :remote@local}
Task.Supervisor.async(supervisor, MyMod, :my_fun, [arg1, arg2, arg3])
Note that, when working with distributed tasks, one should use the
`Task.Supervisor.async/5` function that expects explicit module, function,
and arguments, instead of `Task.Supervisor.async/3` that works with anonymous
functions. That's because anonymous functions expect the same module version
to exist on all involved nodes. Check the `Agent` module documentation for
more information on distributed processes as the limitations described there
apply to the whole ecosystem.
## Statically supervised tasks
The `Task` module implements the `child_spec/1` function, which
allows it to be started directly under a regular `Supervisor` -
instead of a `Task.Supervisor` - by passing a tuple with a function
to run:
Supervisor.start_link([
{Task, fn -> :some_work end}
], strategy: :one_for_one)
This is often useful when you need to execute some steps while
setting up your supervision tree. For example: to warm up caches,
log the initialization status, and such.
If you don't want to put the Task code directly under the `Supervisor`,
you can wrap the `Task` in its own module, similar to how you would
do with a `GenServer` or an `Agent`:
defmodule MyTask do
use Task
def start_link(arg) do
Task.start_link(__MODULE__, :run, [arg])
end
def run(arg) do
# ...
end
end
And then passing it to the supervisor:
Supervisor.start_link([
{MyTask, arg}
], strategy: :one_for_one)
Since these tasks are supervised and not directly linked to the caller,
they cannot be awaited on. By default, the functions `Task.start/1`
and `Task.start_link/1` are for fire-and-forget tasks, where you don't
care about the results or if it completes successfully or not.
`use Task` defines a `child_spec/1` function, allowing the
defined module to be put under a supervision tree. The generated
`child_spec/1` can be customized with the following options:
* `:id` - the child specification identifier, defaults to the current module
* `:restart` - when the child should be restarted, defaults to `:temporary`
* `:shutdown` - how to shut down the child, either immediately or by giving it time to shut down
Opposite to `GenServer`, `Agent` and `Supervisor`, a Task has
a default `:restart` of `:temporary`. This means the task will
not be restarted even if it crashes. If you desire the task to
be restarted for non-successful exits, do:
use Task, restart: :transient
If you want the task to always be restarted:
use Task, restart: :permanent
See the "Child specification" section in the `Supervisor` module
for more detailed information. The `@doc` annotation immediately
preceding `use Task` will be attached to the generated `child_spec/1`
function.
## Ancestor and Caller Tracking
Whenever you start a new process, Elixir annotates the parent of that process
through the `$ancestors` key in the process dictionary. This is often used to
track the hierarchy inside a supervision tree.
For example, we recommend developers to always start tasks under a supervisor.
This provides more visibility and allows you to control how those tasks are
terminated when a node shuts down. That might look something like
`Task.Supervisor.start_child(MySupervisor, task_function)`. This means
that, although your code is the one invoking the task, the actual ancestor of
the task is the supervisor, as the supervisor is the one effectively starting it.
To track the relationship between your code and the task, we use the `$callers`
key in the process dictionary. Therefore, assuming the `Task.Supervisor` call
above, we have:
[your code] -- calls --> [supervisor] ---- spawns --> [task]
Which means we store the following relationships:
[your code] [supervisor] <-- ancestor -- [task]
^ |
|--------------------- caller ---------------------|
The list of callers of the current process can be retrieved from the Process
dictionary with `Process.get(:"$callers")`. This will return either `nil` or
a list `[pid_n, ..., pid2, pid1]` with at least one entry Where `pid_n` is
the PID that called the current process, `pid2` called `pid_n`, and `pid2` was
called by `pid1`.
If a task crashes, the callers field is included as part of the log message
metadata under the `:callers` key.
"""
@doc """
The Task struct.
It contains these fields:
* `:mfa` - a three-element tuple containing the module, function name,
and arity invoked to start the task in `async/1` and `async/3`
* `:owner` - the PID of the process that started the task
* `:pid` - the PID of the task process; `nil` if the task does
not use a task process
* `:ref` - the task monitor reference
"""
@enforce_keys [:mfa, :owner, :pid, :ref]
defstruct @enforce_keys
@typedoc """
The Task type.
See [`%Task{}`](`__struct__/0`) for information about each field of the structure.
"""
@type t :: %__MODULE__{
mfa: mfa(),
owner: pid(),
pid: pid() | nil,
ref: reference()
}
defguardp is_timeout(timeout)
when timeout == :infinity or (is_integer(timeout) and timeout >= 0)
@doc """
Returns a specification to start a task under a supervisor.
`arg` is passed as the argument to `Task.start_link/1` in the `:start` field
of the spec.
For more information, see the `Supervisor` module,
the `Supervisor.child_spec/2` function and the `t:Supervisor.child_spec/0` type.
"""
@doc since: "1.5.0"
@spec child_spec(term) :: Supervisor.child_spec()
def child_spec(arg) do
%{
id: Task,
start: {Task, :start_link, [arg]},
restart: :temporary
}
end
@doc false
defmacro __using__(opts) do
quote location: :keep, bind_quoted: [opts: opts] do
unless Module.has_attribute?(__MODULE__, :doc) do
@doc """
Returns a specification to start this module under a supervisor.
`arg` is passed as the argument to `Task.start_link/1` in the `:start` field
of the spec.
For more information, see the `Supervisor` module,
the `Supervisor.child_spec/2` function and the `t:Supervisor.child_spec/0` type.
"""
end
def child_spec(arg) do
default = %{
id: __MODULE__,
start: {__MODULE__, :start_link, [arg]},
restart: :temporary
}
Supervisor.child_spec(default, unquote(Macro.escape(opts)))
end
defoverridable child_spec: 1
end
end
@doc """
Starts a task as part of a supervision tree with the given `fun`.
`fun` must be a zero-arity anonymous function.
This is used to start a statically supervised task under a supervision tree.
"""
@spec start_link((() -> any)) :: {:ok, pid}
def start_link(fun) when is_function(fun, 0) do
start_link(:erlang, :apply, [fun, []])
end
@doc """
Starts a task as part of a supervision tree with the given
`module`, `function`, and `args`.
This is used to start a statically supervised task under a supervision tree.
"""
@spec start_link(module, atom, [term]) :: {:ok, pid}
def start_link(module, function, args)
when is_atom(module) and is_atom(function) and is_list(args) do
mfa = {module, function, args}
Task.Supervised.start_link(get_owner(self()), get_callers(self()), mfa)
end
@doc """
Starts a task.
`fun` must be a zero-arity anonymous function.
This should only used when the task is used for side-effects
(like I/O) and you have no interest on its results nor if it
completes successfully.
If the current node is shutdown, the node will terminate even
if the task was not completed. For this reason, we recommend
to use `Task.Supervisor.start_child/2` instead, which allows
you to control the shutdown time via the `:shutdown` option.
"""
@spec start((() -> any)) :: {:ok, pid}
def start(fun) when is_function(fun, 0) do
start(:erlang, :apply, [fun, []])
end
@doc """
Starts a task.
This should only used when the task is used for side-effects
(like I/O) and you have no interest on its results nor if it
completes successfully.
If the current node is shutdown, the node will terminate even
if the task was not completed. For this reason, we recommend
to use `Task.Supervisor.start_child/2` instead, which allows
you to control the shutdown time via the `:shutdown` option.
"""
@spec start(module, atom, [term]) :: {:ok, pid}
def start(module, function_name, args)
when is_atom(module) and is_atom(function_name) and is_list(args) do
mfa = {module, function_name, args}
Task.Supervised.start(get_owner(self()), get_callers(self()), mfa)
end
@doc """
Starts a task that must be awaited on.
`fun` must be a zero-arity anonymous function. This function
spawns a process that is linked to and monitored by the caller
process. A `Task` struct is returned containing the relevant
information. Developers must eventually call `Task.await/2` or
`Task.yield/2` followed by `Task.shutdown/2` on the returned task.
Read the `Task` module documentation for more information about
the general usage of async tasks.
## Linking
This function spawns a process that is linked to and monitored
by the caller process. The linking part is important because it
aborts the task if the parent process dies. It also guarantees
the code before async/await has the same properties after you
add the async call. For example, imagine you have this:
x = heavy_fun()
y = some_fun()
x + y
Now you want to make the `heavy_fun()` async:
x = Task.async(&heavy_fun/0)
y = some_fun()
Task.await(x) + y
As before, if `heavy_fun/0` fails, the whole computation will
fail, including the caller process. If you don't want the task
to fail then you must change the `heavy_fun/0` code in the
same way you would achieve it if you didn't have the async call.
For example, to either return `{:ok, val} | :error` results or,
in more extreme cases, by using `try/rescue`. In other words,
an asynchronous task should be thought of as an extension of the
caller process rather than a mechanism to isolate it from all errors.
If you don't want to link the caller to the task, then you
must use a supervised task with `Task.Supervisor` and call
`Task.Supervisor.async_nolink/2`.
In any case, avoid any of the following:
* Setting `:trap_exit` to `true` - trapping exits should be
used only in special circumstances as it would make your
process immune to not only exits from the task but from
any other processes.
Moreover, even when trapping exits, calling `await` will
still exit if the task has terminated without sending its
result back.
* Unlinking the task process started with `async`/`await`.
If you unlink the processes and the task does not belong
to any supervisor, you may leave dangling tasks in case
the caller process dies.
## Metadata
The task created with this function stores `:erlang.apply/2` in
its `:mfa` metadata field, which is used internally to apply
the anonymous function. Use `async/3` if you want another function
to be used as metadata.
"""
@spec async((() -> any)) :: t
def async(fun) when is_function(fun, 0) do
async(:erlang, :apply, [fun, []])
end
# TODO: Remove conditional on Erlang/OTP 24
@compile {:no_warn_undefined, {:erlang, :monitor, 3}}
@doc """
Starts a task that must be awaited on.
Similar to `async/1` except the function to be started is
specified by the given `module`, `function_name`, and `args`.
The `module`, `function_name`, and its arity are stored as
a tuple in the `:mfa` field for reflection purposes.
"""
@spec async(module, atom, [term]) :: t
def async(module, function_name, args)
when is_atom(module) and is_atom(function_name) and is_list(args) do
mfargs = {module, function_name, args}
owner = self()
{:ok, pid} = Task.Supervised.start_link(get_owner(owner), :nomonitor)
{reply_to, ref} =
if function_exported?(:erlang, :monitor, 3) do
ref = :erlang.monitor(:process, pid, alias: :demonitor)
{ref, ref}
else
{owner, Process.monitor(pid)}
end
send(pid, {owner, ref, reply_to, get_callers(owner), mfargs})
%Task{pid: pid, ref: ref, owner: owner, mfa: {module, function_name, length(args)}}
end
@doc """
Starts a task that immediately completes with the given `result`.
Unlike `async/1`, this task does not spawn a linked process. It can
be awaited or yielded like any other task.
## Usage
In some cases, it is useful to create a "completed" task that represents
a task that has already run and generated a result. For example, when
processing data you may be able to determine that certain inputs are
invalid before dispatching them for further processing:
def process(data) do
tasks =
for entry <- data do
if invalid_input?(entry) do
Task.completed({:error, :invalid_input})
else
Task.async(fn -> further_process(entry) end)
end
end
Task.await_many(tasks)
end
In many cases, `Task.completed/1` may be avoided in favor of returning the
result directly. You should generally only require this variant when working
with mixed asynchrony, when a group of inputs will be handled partially
synchronously and partially asynchronously.
"""
@doc since: "1.13.0"
@spec completed(any) :: t
def completed(result) do
ref = make_ref()
owner = self()
# "complete" the task immediately
send(owner, {ref, result})
%Task{pid: nil, ref: ref, owner: owner, mfa: {Task, :completed, 1}}
end
@doc """
Returns a stream where the given function (`module` and `function_name`)
is mapped concurrently on each element in `enumerable`.
Each element of `enumerable` will be prepended to the given `args` and
processed by its own task. Those tasks will be linked to an intermediate
process that is then linked to the caller process. This means a failure
in a task terminates the caller process and a failure in the caller
process terminates all tasks.
When streamed, each task will emit `{:ok, value}` upon successful
completion or `{:exit, reason}` if the caller is trapping exits.
It's possible to have `{:exit, {element, reason}}` for exits
using the `:zip_input_on_exit` option. The order of results depends
on the value of the `:ordered` option.
The level of concurrency and the time tasks are allowed to run can
be controlled via options (see the "Options" section below).
Consider using `Task.Supervisor.async_stream/6` to start tasks
under a supervisor. If you find yourself trapping exits to ensure
errors in the tasks do not terminate the caller process, consider
using `Task.Supervisor.async_stream_nolink/6` to start tasks that
are not linked to the caller process.
## Options
* `:max_concurrency` - sets the maximum number of tasks to run
at the same time. Defaults to `System.schedulers_online/0`.
* `:ordered` - whether the results should be returned in the same order
as the input stream. When the output is ordered, Elixir may need to
buffer results to emit them in the original order. Setting this option
to false disables the need to buffer at the cost of removing ordering.
This is also useful when you're using the tasks only for the side effects.
Note that regardless of what `:ordered` is set to, the tasks will
process asynchronously. If you need to process elements in order,
consider using `Enum.map/2` or `Enum.each/2` instead. Defaults to `true`.
* `:timeout` - the maximum amount of time (in milliseconds or `:infinity`)
each task is allowed to execute for. Defaults to `5000`.
* `:on_timeout` - what to do when a task times out. The possible
values are:
* `:exit` (default) - the caller (the process that spawned the tasks) exits.
* `:kill_task` - the task that timed out is killed. The value
emitted for that task is `{:exit, :timeout}`.
* `:zip_input_on_exit` - (since v1.14.0) adds the original
input to `:exit` tuples. The value emitted for that task is
`{:exit, {input, reason}}`, where `input` is the collection element
that caused an exited during processing. Defaults to `false`.
## Example
Let's build a stream and then enumerate it:
stream = Task.async_stream(collection, Mod, :expensive_fun, [])
Enum.to_list(stream)
The concurrency can be increased or decreased using the `:max_concurrency`
option. For example, if the tasks are IO heavy, the value can be increased:
max_concurrency = System.schedulers_online() * 2
stream = Task.async_stream(collection, Mod, :expensive_fun, [], max_concurrency: max_concurrency)
Enum.to_list(stream)
If you do not care about the results of the computation, you can run
the stream with `Stream.run/1`. Also set `ordered: false`, as you don't
care about the order of the results either:
stream = Task.async_stream(collection, Mod, :expensive_fun, [], ordered: false)
Stream.run(stream)
## First async tasks to complete
You can also use `async_stream/3` to execute M tasks and find the N tasks
to complete. For example:
[
&heavy_call_1/0,
&heavy_call_2/0,
&heavy_call_3/0
]
|> Task.async_stream(fn fun -> fun.() end, ordered: false, max_concurrency: 3)
|> Stream.filter(&match?({:ok, _}, &1))
|> Enum.take(2)
In the example above, we are executing three tasks and waiting for the
first 2 to complete. We use `Stream.filter/2` to restrict ourselves only
to successfully completed tasks, and then use `Enum.take/2` to retrieve
N items. Note it is important to set both `ordered: false` and
`max_concurrency: M`, where M is the number of tasks, to make sure all
calls execute concurrently.
### Attention: unbound async + take
If you want to potentially process a high number of items and keep only
part of the results, you may end-up processing more items than desired.
Let's see an example:
1..100
|> Task.async_stream(fn i ->
Process.sleep(100)
IO.puts(to_string(i))
end)
|> Enum.take(10)
Running the example above in a machine with 8 cores will process 16 items,
even though you want only 10 elements, since `async_stream/3` process items
concurrently. That's because it will process 8 elements at once. Then all 8
elements complete at roughly the same time, causing 8 elements to be kicked
off for processing. Out of these extra 8, only 2 will be used, and the rest
will be terminated.
Depending on the problem, you can filter or limit the number of elements
upfront:
1..100
|> Stream.take(10)
|> Task.async_stream(fn i ->
Process.sleep(100)
IO.puts(to_string(i))
end)
|> Enum.to_list()
In other cases, you likely want to tweak `:max_concurrency` to limit how
many elements may be over processed at the cost of reducing concurrency.
You can also set the number of elements to take to be a multiple of
`:max_concurrency`. For instance, setting `max_concurrency: 5` in the
example above.
"""
@doc since: "1.4.0"
@spec async_stream(Enumerable.t(), module, atom, [term], keyword) :: Enumerable.t()
def async_stream(enumerable, module, function_name, args, options \\ [])
when is_atom(module) and is_atom(function_name) and is_list(args) do
build_stream(enumerable, {module, function_name, args}, options)
end
@doc """
Returns a stream that runs the given function `fun` concurrently
on each element in `enumerable`.
Works the same as `async_stream/5` but with an anonymous function instead of a
module-function-arguments tuple. `fun` must be a one-arity anonymous function.
Each `enumerable` element is passed as argument to the given function `fun` and
processed by its own task. The tasks will be linked to the caller process, similarly
to `async/1`.
## Example
Count the code points in each string asynchronously, then add the counts together using reduce.
iex> strings = ["long string", "longer string", "there are many of these"]
iex> stream = Task.async_stream(strings, fn text -> text |> String.codepoints() |> Enum.count() end)
iex> Enum.reduce(stream, 0, fn {:ok, num}, acc -> num + acc end)
47
See `async_stream/5` for discussion, options, and more examples.
"""
@doc since: "1.4.0"
@spec async_stream(Enumerable.t(), (term -> term), keyword) :: Enumerable.t()
def async_stream(enumerable, fun, options \\ [])
when is_function(fun, 1) and is_list(options) do
build_stream(enumerable, fun, options)
end
defp build_stream(enumerable, fun, options) do
fn acc, acc_fun ->
owner = get_owner(self())
Task.Supervised.stream(enumerable, acc, acc_fun, get_callers(self()), fun, options, fn ->
{:ok, pid} = Task.Supervised.start_link(owner, :nomonitor)
{:ok, :link, pid}
end)
end
end
# Returns a tuple with the node where this is executed and either the
# registered name of the given PID or the PID of where this is executed. Used
# when exiting from tasks to print out from where the task was started.
defp get_owner(pid) do
self_or_name =
case Process.info(pid, :registered_name) do
{:registered_name, name} when is_atom(name) -> name
_ -> pid
end
{node(), self_or_name, pid}
end
defp get_callers(owner) do
case :erlang.get(:"$callers") do
[_ | _] = list -> [owner | list]
_ -> [owner]
end
end
@doc ~S"""
Awaits a task reply and returns it.
In case the task process dies, the caller process will exit with the same
reason as the task.
A timeout, in milliseconds or `:infinity`, can be given with a default value
of `5000`. If the timeout is exceeded, then the caller process will exit.
If the task process is linked to the caller process which is the case when
a task is started with `async`, then the task process will also exit. If the
task process is trapping exits or not linked to the caller process, then it
will continue to run.
This function assumes the task's monitor is still active or the monitor's
`:DOWN` message is in the message queue. If it has been demonitored, or the
message already received, this function will wait for the duration of the
timeout awaiting the message.
This function can only be called once for any given task. If you want
to be able to check multiple times if a long-running task has finished
its computation, use `yield/2` instead.
## Examples
iex> task = Task.async(fn -> 1 + 1 end)
iex> Task.await(task)
2
## Compatibility with OTP behaviours
It is not recommended to `await` a long-running task inside an OTP
behaviour such as `GenServer`. Instead, you should match on the message
coming from a task inside your `c:GenServer.handle_info/2` callback.
A GenServer will receive two messages on `handle_info/2`:
* `{ref, result}` - the reply message where `ref` is the monitor
reference returned by the `task.ref` and `result` is the task
result
* `{:DOWN, ref, :process, pid, reason}` - since all tasks are also
monitored, you will also receive the `:DOWN` message delivered by
`Process.monitor/1`. If you receive the `:DOWN` message without a
a reply, it means the task crashed
Another consideration to have in mind is that tasks started by `Task.async/1`
are always linked to their callers and you may not want the GenServer to
crash if the task crashes. Therefore, it is preferable to instead use
`Task.Supervisor.async_nolink/3` inside OTP behaviours. For completeness, here
is an example of a GenServer that start tasks and handles their results:
defmodule GenServerTaskExample do
use GenServer
def start_link(opts) do
GenServer.start_link(__MODULE__, :ok, opts)
end
def init(_opts) do
# We will keep all running tasks in a map
{:ok, %{tasks: %{}}}
end
# Imagine we invoke a task from the GenServer to access a URL...
def handle_call(:some_message, _from, state) do
url = ...
task = Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn -> fetch_url(url) end)
# After we start the task, we store its reference and the url it is fetching
state = put_in(state.tasks[task.ref], url)
{:reply, :ok, state}
end
# If the task succeeds...
def handle_info({ref, result}, state) do
# The task succeed so we can cancel the monitoring and discard the DOWN message
Process.demonitor(ref, [:flush])
{url, state} = pop_in(state.tasks[ref])
IO.puts "Got #{inspect(result)} for URL #{inspect url}"
{:noreply, state}
end
# If the task fails...
def handle_info({:DOWN, ref, _, _, reason}, state) do
{url, state} = pop_in(state.tasks[ref])
IO.puts "URL #{inspect url} failed with reason #{inspect(reason)}"
{:noreply, state}
end
end
With the server defined, you will want to start the task supervisor
above and the GenServer in your supervision tree:
children = [
{Task.Supervisor, name: MyApp.TaskSupervisor},
{GenServerTaskExample, name: MyApp.GenServerTaskExample}
]
Supervisor.start_link(children, strategy: :one_for_one)
"""
@spec await(t, timeout) :: term
def await(%Task{ref: ref, owner: owner} = task, timeout \\ 5000) when is_timeout(timeout) do
if owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
receive do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
reply
{:DOWN, ^ref, _, proc, reason} ->
exit({reason(reason, proc), {__MODULE__, :await, [task, timeout]}})
after
timeout ->
Process.demonitor(ref, [:flush])
exit({:timeout, {__MODULE__, :await, [task, timeout]}})
end
end
@doc """
Ignores an existing task.
This means the task will continue running, but it will be unlinked
and you can no longer yield, await or shut it down.
Returns `{:ok, reply}` if the reply is received before ignoring the task,
`{:exit, reason}` if the task died before ignoring it, otherwise `nil`.
Important: avoid using [`Task.async/1,3`](`async/1`) and then immediately ignoring
the task. If you want to start tasks you don't care about their
results, use `Task.Supervisor.start_child/2` instead.
Requires Erlang/OTP 24+.
"""
@doc since: "1.13.0"
def ignore(%Task{ref: ref, pid: pid, owner: owner} = task) do
unless function_exported?(:erlang, :monitor, 3) do
raise "Task.ignore/1 requires Erlang/OTP 24+"
end
if owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
receive do
{^ref, reply} ->
Process.unlink(pid)
Process.demonitor(ref, [:flush])
{:ok, reply}
{:DOWN, ^ref, _, proc, :noconnection} ->
exit({reason(:noconnection, proc), {__MODULE__, :ignore, [task]}})
{:DOWN, ^ref, _, _, reason} ->
{:exit, reason}
after
0 ->
Process.unlink(pid)
Process.demonitor(ref, [:flush])
nil
end
end
@doc """
Awaits replies from multiple tasks and returns them.
This function receives a list of tasks and waits for their replies in the
given time interval. It returns a list of the results, in the same order as
the tasks supplied in the `tasks` input argument.
If any of the task processes dies, the caller process will exit with the same
reason as that task.
A timeout, in milliseconds or `:infinity`, can be given with a default value
of `5000`. If the timeout is exceeded, then the caller process will exit.
Any task processes that are linked to the caller process (which is the case
when a task is started with `async`) will also exit. Any task processes that
are trapping exits or not linked to the caller process will continue to run.
This function assumes the tasks' monitors are still active or the monitor's
`:DOWN` message is in the message queue. If any tasks have been demonitored,
or the message already received, this function will wait for the duration of
the timeout.
This function can only be called once for any given task. If you want to be
able to check multiple times if a long-running task has finished its
computation, use `yield_many/2` instead.
## Compatibility with OTP behaviours
It is not recommended to `await` long-running tasks inside an OTP behaviour
such as `GenServer`. See `await/2` for more information.
## Examples
iex> tasks = [
...> Task.async(fn -> 1 + 1 end),
...> Task.async(fn -> 2 + 3 end)
...> ]
iex> Task.await_many(tasks)
[2, 5]
"""
@doc since: "1.11.0"
@spec await_many([t], timeout) :: [term]
def await_many(tasks, timeout \\ 5000) when is_timeout(timeout) do
awaiting =
for task <- tasks, into: %{} do
%Task{ref: ref, owner: owner} = task
if owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
{ref, true}
end
timeout_ref = make_ref()
timer_ref =
if timeout != :infinity do
Process.send_after(self(), timeout_ref, timeout)
end
try do
await_many(tasks, timeout, awaiting, %{}, timeout_ref)
after
timer_ref && Process.cancel_timer(timer_ref)
receive do: (^timeout_ref -> :ok), after: (0 -> :ok)
end
end
defp await_many(tasks, _timeout, awaiting, replies, _timeout_ref)
when map_size(awaiting) == 0 do
for %{ref: ref} <- tasks, do: Map.fetch!(replies, ref)
end
defp await_many(tasks, timeout, awaiting, replies, timeout_ref) do
receive do
^timeout_ref ->
demonitor_pending_tasks(awaiting)
exit({:timeout, {__MODULE__, :await_many, [tasks, timeout]}})
{:DOWN, ref, _, proc, reason} when is_map_key(awaiting, ref) ->
demonitor_pending_tasks(awaiting)
exit({reason(reason, proc), {__MODULE__, :await_many, [tasks, timeout]}})
{ref, reply} when is_map_key(awaiting, ref) ->
Process.demonitor(ref, [:flush])
await_many(
tasks,
timeout,
Map.delete(awaiting, ref),
Map.put(replies, ref, reply),
timeout_ref
)
end
end
defp demonitor_pending_tasks(awaiting) do
Enum.each(awaiting, fn {ref, _} ->
Process.demonitor(ref, [:flush])
end)
end
@doc false
@deprecated "Pattern match directly on the message instead"
def find(tasks, {ref, reply}) when is_reference(ref) do
Enum.find_value(tasks, fn
%Task{ref: ^ref} = task ->
Process.demonitor(ref, [:flush])
{reply, task}
%Task{} ->
nil
end)
end
def find(tasks, {:DOWN, ref, _, proc, reason} = msg) when is_reference(ref) do
find = fn %Task{ref: task_ref} -> task_ref == ref end
if Enum.find(tasks, find) do
exit({reason(reason, proc), {__MODULE__, :find, [tasks, msg]}})
end
end