vrod

vrod

Using Task.start with receive -- is this the same as Task.async?

Hello! I am studying the Task module and I am trying to teach myself some patterns of concurrency in Elixir. I found something like this while reading the documentation for Process.sleep/1:

Task.start_link(fn ->
      Process.sleep(:timer.seconds(1))
      send(parent, :work_is_done)
end)

receive do
  :work_is_done -> IO.puts("Task complete!")
after
  2_000 -> IO.puts("Operation timed out.")
end

My question is: is this the same as using Task.async?


async_task = Task.async(fn ->
      Process.sleep(:timer.seconds(1))
      :work_is_done
end)

val = Task.await(async_task)
IO.inspect(val)
# :work_is_done

So this gives me 3 questions (related) that I hope someone can explain to me:

  1. Does Task.await function the same way as the send + receive example? (I like the syntax of Task.async and Task.await, but I want to make sure this is only syntax difference)
  2. I tried doing send/recieve from Task.start/1 and it seems to work the same as Task.start_link/1. Is there case where Task.start/1 must be used or case where Task.start_link/1 must be used?
  3. If I have a list of tasks, is it always better to use Task.async_stream? I tried using Enum.map to put many Task.asyncs together and it seems like Task.async_stream is a better way.

Thank you! I want to try to understand this well before I study GenServers.

Most Liked

ityonemo

ityonemo

It’s not exactly the same. Task.async is a bit smarter than that, because when you call it it saves a reference. When the await catches the message, it pattern matches against the reference to make sure it’s matching against the right task.

This protects against the situation where tasks cross streams. In the Task implementation, you can do this:

1..10
|> Enum.map(&Task.async(fn ->
  Process.sleep(Enum.random(1..200))
  &1
end))
|> Enum.map(&Task.await/1)

And your 1…10 will come back in order; they will not with your await implementation.

Check the elixir code for task.await: https://github.com/elixir-lang/elixir/blob/v1.10.4/lib/elixir/lib/task.ex#L418

This pattern will reappear in gen_server.call, so understanding it is probably a good idea :smiley:

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

We're in Beta

About us Mission Statement