Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Created July 17, 2023 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pmarreck/4cc8f2f55a561ebce2012085a3a631f0 to your computer and use it in GitHub Desktop.
Save pmarreck/4cc8f2f55a561ebce2012085a3a631f0 to your computer and use it in GitHub Desktop.
Elixir concurrency demo: 1 million process spawn and garbage-collect.
#!/usr/bin/env elixir
# make sure to bump max erlang processes limit first:
# export ERL_FLAGS="+P 2000000"
defmodule Concurrency do
def millions_of_us(n) do
receive do
{sender_pid, message} ->
Process.sleep(:rand.uniform(2000))
send(sender_pid, "Process #{n} received message #{message}")
end
end
def demo() do
1..1_000_000
|> Enum.map(fn n -> spawn(Concurrency, :millions_of_us, [n]) end)
|> Enum.each(fn pid -> send(pid, {self(), "Hello!"}) end)
receive_messages()
end
defp receive_messages do
receive do
message ->
IO.puts(message)
receive_messages()
after
3000 -> # After 3 seconds of no messages, end the function.
IO.puts("No messages for 3 seconds. Done receiving messages.")
end
end
end && IO.puts("Concurrency module loaded.")
Process.sleep(3000)
Concurrency.demo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment