Purpose of Process.sleep(:infinity)

Hi all

Could someone please tell me, what is the purpose of Process.sleep(:infinity).

The code is from:

defmodule A do
  use GenStage

  def init(counter) do
    {:producer, counter}
  end

  def handle_demand(demand, counter) when demand > 0 do
    # If the counter is 3 and we ask for 2 items, we will
    # emit the items 3 and 4, and set the state to 5.
    events = Enum.to_list(counter..counter+demand-1)
    {:noreply, events, counter + demand}
  end
end


defmodule C do
  use GenStage

  def init(:ok) do
    {:consumer, :the_state_does_not_matter}
  end

  def handle_events(events, _from, state) do
    # Wait for a second.
    :timer.sleep(1000)

    # Inspect the events.
    IO.inspect(events)

    # We are a consumer, so we would never emit items.
    {:noreply, [], state}
  end
end

{:ok, a} = GenStage.start_link(A, 0)   # starting from zero
{:ok, c} = GenStage.start_link(C, :ok) # state does not matter

GenStage.sync_subscribe(c, to: a)
Process.sleep(:infinity)

I read the doc https://hexdocs.pm/elixir/Process.html#sleep/1, it says with infinity with process will be suspended, what does it mean?

Thanks

7 Likes

This is a very good question!

When a process is suspended, it will not respond to any messages anymore, except a few certain system messages (such as a message to wake it up at a later time). Suspending processes manually is something that you won’t encounter often in live code, except deep down in libraries that e.g. perform hot code reloading or debugging.

In this example, it does make sense to suspend the main process, because an Erlang/Elixir program exits as soon as the initial ‘main’ process has finished its execution. Without the Process.sleep(:infinity) line, this example would thus quit right away, without showing any output, as the only thing that the initial process does is to start two other processes.

9 Likes

4 posts were removed as offtopic