spawn
The basic mechanism for spawning new processes is with the auto-imported spawn/1
function:
iex> spawn fn -> 1 + 2 end
#PID<0.43.0>
spawn/1
takes a function which it will execute in another process.
Notice spawn/1
returns a PID (process identifier). At this point, the process you spawned is very likely dead. The spawned process will execute the given function and exit after the function is done:
iex> pid = spawn fn -> 1 + 2 end
#PID<0.44.0>
iex> Process.alive?(pid)
false
Note: you will likely get different process identifiers than the ones we are getting in this guide.
We can retrieve the PID of the current process by calling self/0
:
iex> self()
#PID<0.41.0>
iex> Process.alive?(self())
true
Processes get much more interesting when we are able to send and receive messages.