DEV Community

mridul037
mridul037

Posted on

2 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay