9 Concurrency Basics
9.1 Processes
How can processes communicate with each other to share data? We can use send
to send data to a specific process, and receive
to retrieve data from a a specific process.
9.2 Managing State with Long-lived Processes
defmodule Counter do
# public API
def start_link(initial_count \\ 0) do
Counter, :run, [initial_count])
spawn_link(end
def increment(pid) when is_pid(pid) do
:increment)
send(pid, end
def decrement(pid) when is_pid(pid) do
:decrement)
send(pid, end
def count(pid) when is_pid(pid) do
:count, self()})
send(pid, {
receive do
^pid, count} -> count
{end
end
# implementation
def run(count) do
receive do
-> handler(msg, count)
msg end
|> run()
end
def handler(:increment, count), do: count + 1
def handler(:decrement, count), do: count - 1
def handler({:count, pid}, count) do
send(pid, {self(), count})
countend
end
1)> import Counter
iex(2)> p = start_link()
iex(#PID<0.112.0>
3)> increment(p)
iex(#> :increment
4)> increment(p)
iex(#> :increment
5)> increment(p)
iex(#> :increment
6)> count(p)
iex(#> 3