Skip to content

Commit 44b85be

Browse files
author
José Valim
committed
Add Task.start/1 and Task.start/3
1 parent e344b1f commit 44b85be

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

lib/elixir/lib/task.ex

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,30 @@ defmodule Task do
119119
Task.Supervised.start_link(get_info(self), {mod, fun, args})
120120
end
121121

122+
@doc """
123+
Starts a task.
124+
125+
This is only used when the task is used for side-effects
126+
(i.e. no interest in its return result) and it should not
127+
be linked to the current process.
128+
"""
129+
@spec start(fun) :: {:ok, pid}
130+
def start(fun) do
131+
start(:erlang, :apply, [fun, []])
132+
end
133+
134+
@doc """
135+
Starts a task.
136+
137+
This is only used when the task is used for side-effects
138+
(i.e. no interest in its return result) and it should not
139+
be linked to the current process.
140+
"""
141+
@spec start(module, atom, [term]) :: {:ok, pid}
142+
def start(mod, fun, args) do
143+
Task.Supervised.start(get_info(self), {mod, fun, args})
144+
end
145+
122146
@doc """
123147
Starts a task that can be awaited on.
124148

lib/elixir/lib/task/supervised.ex

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
defmodule Task.Supervised do
22
@moduledoc false
33

4+
def start(info, fun) do
5+
{:ok, :proc_lib.spawn(__MODULE__, :noreply, [info, fun])}
6+
end
7+
48
def start_link(info, fun) do
59
{:ok, :proc_lib.spawn_link(__MODULE__, :noreply, [info, fun])}
610
end

lib/elixir/test/elixir/task_test.exs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,37 @@ defmodule TaskTest do
6161
assert_receive :done
6262
end
6363

64+
test "start/1" do
65+
parent = self()
66+
fun = fn -> wait_and_send(parent, :done) end
67+
{:ok, pid} = Task.start(fun)
68+
69+
{:links, links} = Process.info(self, :links)
70+
refute pid in links
71+
72+
receive do: (:ready -> :ok)
73+
74+
{:name, fun_name} = :erlang.fun_info(fun, :name)
75+
assert {__MODULE__, fun_name, 0} === :proc_lib.translate_initial_call(pid)
76+
77+
send pid, true
78+
assert_receive :done
79+
end
80+
81+
test "start/3" do
82+
{:ok, pid} = Task.start(__MODULE__, :wait_and_send, [self(), :done])
83+
84+
{:links, links} = Process.info(self, :links)
85+
refute pid in links
86+
87+
receive do: (:ready -> :ok)
88+
89+
assert {__MODULE__, :wait_and_send, 2} === :proc_lib.translate_initial_call(pid)
90+
91+
send pid, true
92+
assert_receive :done
93+
end
94+
6495
test "start_link/1" do
6596
parent = self()
6697
fun = fn -> wait_and_send(parent, :done) end

0 commit comments

Comments
 (0)