Timeouts in Erlang
Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in Erlang is straightforward using the timer
module and message passing.
Running this program shows the first operation timing out and the second succeeding.
In this Erlang version:
We use separate processes (created with
spawn
) to simulate the delayed operations instead of goroutines.Instead of channels, we use Erlang’s built-in message passing mechanism.
The
select
statement with timeout is replaced by Erlang’sreceive..after
construct, which allows us to specify a timeout directly.We use
timer:sleep/1
to introduce delays, similar totime.Sleep
in the original example.The
io:format/2
function is used for output, replacingfmt.Println
.
This example demonstrates how to implement timeouts in Erlang, which is a crucial feature for programs that need to bound execution time or interact with external resources.