Skip to content
Elixir

Processos e Mensagens

Spawnar processos leves e enviar mensagens.

#process#actor#message

Code

elixir
# Spawn a process
pid = spawn(fn ->
  receive do
    {:hello, from} ->
      send(from, {:hi, self()})
      receive do
        msg -> IO.puts("Got: #{inspect(msg)}")
      end
    {:bye} ->
      IO.puts("Goodbye!")
  end
end)

# Send a message
send(pid, {:hello, self()})

# Receive (with timeout)
receive do
  {:hi, pid2} -> IO.puts("Received hi from #{inspect(pid2)}")
after
  1000 -> IO.puts("Timeout")
end

# Process info
Process.alive?(pid)  # true/false
Process.list()        # all PIDs

# Link (dies together)
spawn_link(fn -> exit(:boom) end)
# Traps EXIT if Process.flag(:trap_exit, true)