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: elixir/lib/elixir/lib/task.ex at v1.10.4 · elixir-lang/elixir · GitHub

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

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
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
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
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
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement