Skip to content

Instantly share code, notes, and snippets.

@tiagopog
Last active November 14, 2016 06:38
Show Gist options
  • Select an option

  • Save tiagopog/040ae4cadb5ddef74d24487574ceb5f6 to your computer and use it in GitHub Desktop.

Select an option

Save tiagopog/040ae4cadb5ddef74d24487574ceb5f6 to your computer and use it in GitHub Desktop.
Elixir - Kernel.spawn/1 & Async
defmodule AsyncTest do
@contents ["foo", "bar", "foobar"]
@output "async_test"
def run do
File.rm_rf!(@output)
File.mkdir_p!(@output)
@contents
|> Enum.with_index
|> Enum.map(&write_content_async(&1))
|> Enum.map(fn _ ->
receive do
:ok -> :ok
{:error, reason} -> IO.puts :stderr, "Error: #{reason}"
after 3000 ->
IO.puts :stderr, "Timeout"
end
end)
end
def write_content_async(params) do
caller = self()
spawn(fn ->
seconds = :rand.uniform(10) * 1000
:timer.sleep(seconds)
send(caller, write_content(params))
end)
end
def write_content({content, index})do
IO.puts "Write \"#{content}\" into a file"
File.write("#{@output}/test_#{index + 1}.txt", content)
end
end
defmodule AsyncTest2 do
@contents ["foo", "bar", "foobar"]
@output "async_test"
def run do
File.rm_rf!(@output)
File.mkdir_p!(@output)
@contents
|> Enum.with_index
|> Enum.map(&Task.async(fn ->
write_content(&1)
end))
|> Enum.map(&Task.await/1)
end
def write_content({content, index}) do
seconds = :rand.uniform(5) * 1000
:timer.sleep(seconds)
IO.puts "Write \"#{content}\" into a file"
File.write("#{@output}/test_#{index + 1}.txt", content)
end
e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment