Use Livebook to open this notebook and explore new ideas.
It is easy to get started, on your machine or the cloud.
# Elixir Processes and GenServers - Part 1
## 0. Launch
[](https://livebook.dev/run?url=https://github.com/cleaver/genserver_livebook/blob/main/genservers_1.livemd)
## 1. Basic Processes: spawn()
Take a simple operation:
```elixir
1 + 1 |> IO.puts()
```
Let's run it in a different process.
`spawn/1` creates a process and runs code in a provided function.
```elixir
spawn(fn -> 1 + 1 |> IO.puts() end)
```
`spawn/3` lets you specify _module_, _function_, and _args_.
```elixir
defmodule Spawnable do
def add(a, b) do
a + b
|> IO.puts()
end
end
spawn(Spawnable, :add, [7, 8])
```
## 2. Message Passing
A spawned process can listen for messages.
<!-- livebook:{"continue_on_error":true} -->
```elixir
defmodule BilingualGreeter do
def listen_loop do
receive do
# print the greeting
{:bonjour_hi, name} -> IO.puts("Bonjour hi, #{name}")
# exit with reason
{:goodbye} -> exit(:au_revoir)
end
listen_loop()
end
end
```
Spawn the process:
```elixir
greeter_pid = spawn(BilingualGreeter, :listen_loop, [])
```
Send a message:
```elixir
send(greeter_pid, {:bonjour_hi, "Elixir Montréal"})
```
End the listen loop:
```elixir
send(greeter_pid, {:goodbye})
```
Notice that we don't see the exit reason.
## 3. Linking Processes
Let's try again with a linked process:
```elixir
greeter_pid = spawn_link(BilingualGreeter, :listen_loop, [])
```
```elixir
send(greeter_pid, {:bonjour_hi, "Elixir Montréal"})
```
```elixir
send(greeter_pid, {:goodbye})
```
[Next](genservers_2.livemd)
See source