Goroutines in Erlang
On this page
A lightweight thread of execution in Erlang is known as a process. Here’s how you can accomplish similar functionality to goroutines using Erlang.
Explanation and Code Example
A lightweight thread of execution
An Erlang process is a lightweight thread of execution.
Detailed Explanation
Function Definition: We define an Erlang module
goroutines
and export two functionsstart/0
andf/1
.Loop Function: The function
f/1
calls a helper functionloop/2
, iterating 3 times and printing a message each time.Start Function: The
start/0
function demonstrates synchronous call and the concurrent process creation:- Call
f("direct")
synchronously. - Use
spawn/1
to create a new process to callf("process")
, enabling concurrent execution. - Use
spawn/1
to start another process with an anonymous function, printing “going”. - Use
timer:sleep(1000)
to wait for the processes to finish.
- Call
Running the Program
To run the program and see the output:
Expect to see output similar to:
In this example, the spawn/1
function is used to create new concurrent processes, which is how we achieve the concurrency seen with goroutines.