[erlang-questions] When to use gen_server?

Garrett Smith g@REDACTED
Thu Jan 12 17:54:01 CET 2012


On Thu, Jan 12, 2012 at 4:35 AM, eigenfunction <emeka_1978@REDACTED> wrote:
>
>> If you don't need to serialize your data
>> processing requests, don't bother with all that.
>
> Could you pls elaborate more on that? I, Like the OP , sometimes
> have a hard time making a difference between a gen_server and a normal
> process,
> and i end up using normal processes and think that i am doing
> something wrong.
> Can anyone give an example of a case where a gen_server is more useful
> than a normal
> process?

As Robert succinctly put, a gen_server wraps a process. Use gen_server
whenever you want to formalize your process behavior.

Here's a simple low level use of an Erlang process:

  spawn(fun() -> do_work() end)

We do some work in an Erlang process and when we're done the process
exits. Super simple.

We can "formalize" the process by creating a module:

  -module(workers).

  start_work ->
      spawn(fun() -> do_work() end).

This hides the details of doing the work. You can document it, you can
include it in an OTP app that can be used in different system
configurations. Fantastic!

Adding more features to our process-based work system is now a matter
of adding new functions:

  change_work_priority/2
  get_work_status/1
  stop_work/1

To implement these, we'd go through the basic routine: use a loop
function that receives messages, handle message sent from our exported
functions, send replies to callers, etc. You'll see this in every
Erlang textbook.

But at that point, for the cost of a few extra lines of code, we're
better off implementing a gen_server behavior. We can then use OTP
supervisors to start and monitor the process. Even if we don't care
about process restarts (e.g. temporary restart strategy), using OTP
conventions will formalize the process life cycle.

Garrett



More information about the erlang-questions mailing list