vinhnglx / vinhnglx.github.io

0 stars 0 forks source link

TIL_09_June_2017 - Process & Message passing mechanism (Elixir) #3

Open vinhnglx opened 7 years ago

vinhnglx commented 7 years ago

I. Process in Elixir

spawn(fn -> say_hello.("Vincent") end)

Example:

iex > say_hello = fn(your_name) -> 
  Process.sleep(4000)
  "Hello #{your_name}" 
end

iex > Enum.map(1..5, fn(x) -> say_hello.(x) end)
["Hello 1", "Hello 2", "Hello 3", "Hello 4", "Hello 5"] # 20 seconds

iex > query = fn(your_name) ->
  spawn(fn -> IO.puts(say_hello.(your_name)) end)
end

iex > query.("vincent")
"Hello vincent" # 4 seconds

iex > Enum.map(1..5, fn(x) -> query.(x) end)
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
# 4 seconds
vinhnglx commented 7 years ago

II. Message passing mechanism

Processes are completely independent and isolated so how can they communicate? Processes will communicate via messages.

So, in general, the progress will be, for example, we have two processes A and B

Example:

  def receive_msg do
    receive do
      {:message, msg} -> IO.puts "Receive message from #{msg}"
    end
  end

iex(1)> pid = spawn(Practices, :receive_msg, [])
#PID<0.119.0>
iex(2)> send pid, {:message, "ding"}
Receive message from ding
{:message, "ding"}
vinhnglx commented 7 years ago

Can refer #10 for the example