Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

erlang

How to create a process in Erlang

Sharaz Haider

Processes in Erlang

Erlang processes are introduced to achieve high concurrency for program execution. These processes are lightweight and adjust according to the memory size (dynamically shrink and expand) with minimal footprints. Processes in Erlang are quick and easy to create and terminate with low scheduling overhead.

Process creation in Erlang

Let’s have a look at process creation in Erlang. In Erlang, processes are created by calling the spawn() method.

spawn(Module, Name, Args) -> pid()
  Module = Name = atom()
  Args = [X1,...,Xn]
    Xi = term()
Spawn syntax

The spawn() method creates a process and returns the process identifier PID.

On execution of spawn(), module: Name, starts with a list of arguments (primarily blank) provided in Args.

Example

-module(main).

-export([main/0, showStr/1]).


showStr(String) ->
    io:format("~p~n", [String]).

main() ->
    spawn(main, showStr, [green]),
    spawn(main, showStr, [educative]).
Spawn Example

Explanation

  • Line 1: We use the -module() method to create a module main to execute Erlang commands.
  • Line 3: We use the -export() method to define the prototypes of the function we'll create with the number of arguments defined after /.
  • Line 6: The showStr() method is defined with one parameter (string value to print).
  • Line 7: We use io:format to print in Erlang. We use ~p here to print the index of the list, and ~n is used to write a new line.
  • Line 9: The main() method is defined to execute the spawn() method process call.
  • Lines 10–11: We use the showStr() method to call two spawn() requests to create two concurrent processes in order to show the passed string.

RELATED TAGS

erlang

CONTRIBUTOR

Sharaz Haider
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring