Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions lib/elixir/lib/gen_server.ex
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,41 @@ defmodule GenServer do
message arriving, `handle_info/2` is called with `:timeout` as the first
argument.

For example:

defmodule Counter do
use GenServer

@timeout to_timeout(second: 5)

@impl true
def init(count) do
{:ok, count, @timeout}
end

@impl true
def handle_call(:succ, _from, count) do
new_count = count + 1
{:reply, new_count, new_count, @timeout}
end

@impl true
def handle_info(:timeout, count) do
{:stop, :normal, count}
end
end

A `Counter` server will exit with `:normal` if there are no messages in 5 seconds
after the initialization or after the last `succ` call:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't understand what succ stands for, how about naming this :incr since this is a counter?

Copy link
Contributor Author

@dmitrykleymenov dmitrykleymenov May 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://en.wikipedia.org/wiki/Successor_function
I thought succ better explains what is going on, initial thought was to useincr :-)
Should we change it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest to not use abbreviations in documentation. It's clearer to use :success or :increment instead.


{:ok, counter_pid} = GenServer.start(Counter, 50)
GenServer.call(counter_pid, :succ)
#=> 51

# After 5 secs
Process.alive?(counter_pid)
#=> false

## When (not) to use a GenServer

So far, we have learned that a `GenServer` can be used as a supervised process
Expand Down