Erlang - Processes



The granularity of concurrency in Erlang is a process. A process is an activity/task that runs concurrently with and is independent from the other processes. These processes in Erlang are different than the processes and threads most people are familiar with. Erlang processes are lightweight, operate in (memory) isolation from other processes, and are scheduled by Erlang’s Virtual Machine (VM). The creation time of process is very low, the memory footprint of a just spawned process is very small, and a single Erlang VM can have millions of processes running.

A process is created with the help of the spawn method. The general syntax of the method is given below.

Syntax

spawn(Module, Name, Args)

Parameters

  • Module − This is a predefined atom value which must be ?MODULE.

  • Name − This is the name of the function to be called when the process is defined.

  • Args − These are the arguments which need to be sent to the function.

Return Value

Returns the process id of the new process created.

For example

An example of the spawn method is shown in the following program.

-module(helloworld). 
-export([start/0, call/2]). 

call(Arg1, Arg2) -> 
   io:format("~p ~p~n", [Arg1, Arg2]). 
start() -> 
   Pid = spawn(?MODULE, call, ["hello", "process"]), 
   io:fwrite("~p",[Pid]).

The following things need to be noted about the above program.

  • A function called call is defined and will be used to create the process.

  • The spawn method calls the call function with the parameters hello and process.

Output

When we run the above program we will get the following result.

<0.29.0>"hello" "process"

Now let’s look at the other functions which are available with processes.

Sr.No. Methods & Description
1

is_pid

This method is used to determine if a process id exists.

2

is_process_alive

This is called as is_process_alive(Pid). A Pid must refer to a process at the local node.

3

pid_to_list

It converts a process id to a list.

4

registered

Returns a list with the names of all registered processes.

5

self

One of the most commonly used BIF, returns the pid of the calling processes.

6

register

This is used to register a process in the system.

7

whereis

It is called as whereis(Name). Returns the pid of the process that is registered with the name.

8

unregister

This is used to unregister a process in the system.

Advertisements