Run this notebook

Use Livebook to open this notebook and explore new ideas.

It is easy to get started, on your machine or the cloud.

Click below to open and run it in your Livebook at .

(or change your Livebook location)

# Elixir Processes and GenServers - Part 1 ## 0. Launch [![Run in Livebook](https://livebook.dev/badge/v1.svg)](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

Have you already installed Livebook?

If you already installed Livebook, you can configure the default Livebook location where you want to open notebooks.
Livebook up Checking status We can't reach this Livebook (but we saved your preference anyway)
Run notebook

Not yet? Install Livebook in just a minute

Livebook is open source, free, and ready to run anywhere.

Run on your machine

with Livebook Desktop

Run in the cloud

on select platforms

To run on Linux, Docker, embedded devices, or Elixir’s Mix, check our README.

PLATINUM SPONSORS
SPONSORS
Code navigation with go to definition of modules and functions Read More ×