Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Re-registering a process upon restart #16

Closed
doubleyou opened this Issue · 2 comments

2 participants

@doubleyou

Say, I use a simple_one_for_one supervisor that controls a set of processes. Each of those processes is registered by some non-atom name.

Let's write the following in the init/1 function:

init([Name, Options]) ->
    gproc:reg({n, l, Name}, self()),
    ....

But this code will fail upon restart, since gproc won't allow me to register under an already existing name. Okay, let's unregister this name first:

init([Name, Options]) ->
     gproc:unreg({n, l, Name}),
     gproc:reg({n, l, Name}, self()),
    ...

But this will fail too, because if nothing is registered under the given name, gproc:unreg/1 will fail.

So far, I see two ways of working this out, and both seem quite ugly to me:

     catch gproc:unreg({n, l, Name}),
    ....

and

    case gproc:where({n, l, Name}) of
        undefined -> void;
        _ -> gproc:unreg({n, l, Name}
    end,
   ....

The current behavior of gproc:reg/2 and gproc:unreg/1 seems to be actually right, since we gain more control over what we did register and what we didn't. But I still feel that I'm missing something and there is a better way of handling this situation with the existing gproc API.

@uwiger
Owner

Gproc is even more strict than that. Only the registered process can unregister itself.

The question here is whether one wants to be 'sloppy' about name registration or explicit. Gproc is, by design, pretty strict. This means that the sort of 'opportunistic' name registration you're attempting will require a few lines more.

A technique I sometimes use when this is really needed, is to have the name registration as the deciding point at which I either let the process assume its role, or simply let it crash. Just calling gproc:reg({n,l,Name}) will have this 'first-come-first-server' effect.

@doubleyou

Ah, didn't realize that gproc unregisters non-alive processes automatically. Then, my initial assumption was wrong, and you can just do

gproc:reg({n, l, Name}, self()),

inside the init function, and upon restart the process will be registered again.

Thanks for the explanation anyway, didn't have an idea that unregistering works only from the registered process itself. That's a good way, true Erlang's vandalism-proof concept. :)

@doubleyou doubleyou closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.