One of the features that makes Erlang stand out is concurrency. Concurrency means that a processor can handle multiple computations at the same time. To do this, we need to create threads. In a nutshell, a thread is a way that a program can split itself into two more tasks that are running simultaneously. Running programs in threads is quite advantageous. Even if a processor is not multi-threaded, it can still give the impression that two or more programs are running concurrently.
One thing to note here is that in Erlang, the word process, as well as the thread, are used interchangeably. To understand this, we first need to understand what a process is. A program under execution is called a process and its other features include a separate memory, which means that it is secluded from other processes. Therefore, a process cannot directly access shared data among other processes.
On the other hand, threads can be thought of as segments of a process. This indicates that all the threads within the same process have access to the same memory. Threads in Erlang are not able to share data with each other. This is why threads in Erlang are also called processes.
spawn(Module, ThreadName, ArgsList)
Erlang has a built-in function called spawn(Module, ThreadName, ArgsList) for creating threads. It has the following parameters:
Module is simply the name of the module we're using.
ThreadName is self-explanatory, as it can be anything we want.
ArgsList contains the arguments list that is passed to the thread.
The spawn() function returns the process ID (PID).
-module(main).-export([thread/2,main/0]).main() ->spawn(main, thread, [first, 3]),spawn(main, thread, [second, 2]).thread(Var, 0) ->done;thread(Var, Num) ->io:format("~p~n", [Var]),thread(Var, Num - 1).
Line 1: We declare that our code is part of the main module, which can be considered a namespace.
Line 2: This is done to use any of the functions we have declared in our code.
Line 4: This is the main function.
Lines 5–6: The spawn keyword creates a new process and returns its process ID. Its arguments include:
The name of the module i.e. main.
The name of the thread, which we have named thread.
The arguments of the thread. The first argument, Var, is a string to print on the console and the second one, Num, is the number of threads to be created.
Lines 8–9: This is done to stop the recursive creation of threads.
Line 11: We begin implementing the thread.
Line 12: We print the value of Var to the console.
Line 13: We recursively create threads till the value of Num becomes 0.
Free Resources