After seeing the conceptual model of how processes work inside the BEAM, we will now see how we can work with them. Namely, we will cover how to work with processes, how to pass messages between them, and, to showcase how we can use processes to maintain state, we will build a component of our ElixirDrip app, the cache worker.
You create a process by calling the Kernel.spawn/1
function, which receives an anonymous function with no arguments:
iex> self() #PID<0.85.0> iex> spawn(fn -> ...> :timer.sleep(2000) ...> IO.puts "I'm running in process #{inspect(self())}" ...> end) #PID<0.91.0> I'm running in process #PID<0.91.0>
In this example, we're first calling self()
, which returns the PID of the current process. In this case, it returned the PID of the shell process. Then, we use the spawn
function to create a new process. As previously stated, it receives an anonymous function that will run in the newly created...