Elixir
Processes and Messages
Spawn lightweight processes and send messages.
By EZ4Code Team
processactormessage
Code
# 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)Explanation
Elixir processes are lightweight (thousands can run concurrently) — they don't share memory, they communicate via messages. send/receive is the core primitive. receive blocks until a matching message arrives (or after timeout). spawn_link creates a linked process — if one dies, the other does too (unless trapping exits). This is the Actor model on the BEAM VM.
More Elixir Snippets
Pattern Matching
Pattern matching is core to Elixir — used everywhere.
Pipe Operator
Chain function calls with the |> pipe operator.
GenServer
Build stateful server processes with GenServer behaviour.
Supervisors and OTP
Build fault-tolerant supervision trees.
Protocols and Enums
Polymorphism via protocols and the Enum module.
Enum and Stream Operations
Functional collection operations in Elixir.