Adds koans about tasks
This commit is contained in:
49
lib/koans/11_task.ex
Normal file
49
lib/koans/11_task.ex
Normal file
@@ -0,0 +1,49 @@
|
||||
defmodule Tasks do
|
||||
use Koans
|
||||
|
||||
koan "Tasks can be used for asynchronous computations with results" do
|
||||
task = Task.async(fn -> 3 *3 end)
|
||||
do_other_stuff()
|
||||
assert Task.await(task) + 1 == 10
|
||||
end
|
||||
|
||||
koan "if you don't need a result, use start_link/1" do
|
||||
{:ok, pid} = Task.start_link(fn -> 1+1 end)
|
||||
end
|
||||
|
||||
koan "yield returns nil if the task isn't done yet" do
|
||||
handle = Task.async(fn ->
|
||||
:timer.sleep(100)
|
||||
3 * 3
|
||||
end)
|
||||
assert Task.yield(handle, 10) == nil
|
||||
assert Task.await(handle) == 9
|
||||
end
|
||||
|
||||
koan "tasks can be aborted with shutdown" do
|
||||
handle = Task.async(fn ->
|
||||
:timer.sleep(100)
|
||||
3 * 3
|
||||
end)
|
||||
refute Task.shutdown(handle)
|
||||
end
|
||||
|
||||
koan "shutdown will give you an answer if it has it" do
|
||||
handle = Task.async(fn -> 3 * 3 end)
|
||||
:timer.sleep(10)
|
||||
assert Task.shutdown(handle) == {:ok, 9}
|
||||
end
|
||||
|
||||
koan "you can yield to multiple tasks at once and extract the results" do
|
||||
squares = [1,2,3,4]
|
||||
|> Enum.map(fn(number) -> Task.async(fn -> number * number end) end)
|
||||
|> Task.yield_many(100)
|
||||
|> Enum.map(fn({_task,{:ok, result}}) -> result end)
|
||||
|
||||
assert squares == [1,4,9,16]
|
||||
end
|
||||
|
||||
def do_other_stuff do
|
||||
:timer.sleep(50)
|
||||
end
|
||||
end
|
||||
@@ -9,7 +9,8 @@ defmodule Runner do
|
||||
Arithmetic,
|
||||
Structs,
|
||||
PatternMatching,
|
||||
Processes
|
||||
Processes,
|
||||
Tasks
|
||||
]
|
||||
|
||||
def run do
|
||||
|
||||
Reference in New Issue
Block a user