DEV Community

mridul037
mridul037

Posted on

Processes in Elixir

spawn

The basic mechanism for spawning new processes is the auto-imported spawn/1 function:

iex> spawn(fn -> 1 + 2 end)
# PID<0.43.0>

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:

Can we see if its dead or alive

iex> pid = spawn(fn -> 1 + 2 end)
#PID<0.44.0>
iex> Process.alive?(pid)
false 
Enter fullscreen mode Exit fullscreen mode
Lets send a Message from one process to another

We can retrieve the PID of the current process by calling self :

iex(6)> parent=self()
#PID<0.103.0>  
Enter fullscreen mode Exit fullscreen mode

Sender

iex(7)> spawn(fn->send(parent,{:hello,self()}) end) 
#PID<0.115.0> 
Enter fullscreen mode Exit fullscreen mode

When a message is sent to a process, the message is stored in the process mailbox. The receive/1 block goes through the current process mailbox searching for a message that matches any of the given patterns

Receiver

iex(8)> receive do                                      
...(8)> {:hello,pid}->"Got hello form #{inspect pid}"  
...(8)> end                                               
"Got hello form #PID<0.115.0>"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)