Process scheduling in Erlang

I have the following queries. Please clarify.

  1. Which approach is followed to schedule Erlang processes? Pre-emptive or cooperative?

  2. If Pre-emptive is supported, how are the process pre-empted? Is it by time-slicing? or by other means?

  3. I have planned to write a worker for event processing using Erlang process. The worker supports two types of messages namely START & STOP – one to start event processing and another to stop event processing. As part of event processing, it calls a blocking call in an infinite loop to receive the events. The infinite loop loops based on a flag. Upon receiving the STOP message, the worker sets the flag which should result in the infinite loop exiting. This design works in Java since it uses Time-slice based pre-emptive scheduling. Will this design works in Erlang?


Preemptive (with NIF caveats), based on reduction count. See this book that explains scheduling in details: The Erlang Runtime System (it’s a bit dated but general principles are still there).

Your “worker” implementation is a classic Erlang’s gen_server. You can even generate the scaffolding in IntelliJ Idea (with Erlang plugin installed), and it will look similar to this:


-export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2]).

-record(worker_state, {}).

start_link() ->
    gen_server:start_link(?MODULE, [], []).

init([]) ->
    {ok, #worker_state{}}.

handle_call(_Request, _From, #worker_state{} = State) ->
    {reply, ok, State}.

handle_cast(_Request, State = #worker_state{}) ->
    {noreply, State}.

handle_info({external_event, Args}, #worker_state{} = State) ->
    {noreply, State}.

The last function (handle_info) is what processes your “external events”. You don’t need to write the event loop yourself, it’s a part of the OTP.


Thanks Max for the pointers. Let me check them.

1 Like