[erlang-questions] Singleton Process

Edward Stow ed.stow@REDACTED
Tue Feb 3 11:26:24 CET 2009


Bernard

2009/2/3 Bernard Duggan <bernie@REDACTED>:
> Hi Edward,
>        Your code is a pretty reasonable attempt at a basic implementation (and
> I don't mean that in any derogatory or rude sense - much of my code from
> not very long ago follows a similar pattern).
>        The most obvious problem I can see with it is the race condition in
> start() - if two processes call next_id() at the same time, they could
> both call whereis(counter) and receive 'undefined' as the response -
> they'd both then try to spawn  and register the process, and while both
> spawns would succeed, only the first register() would.  Generally I find
> it's best to spawn such "singleton" (I have no idea if that's the
> correct terminology, sorry) processes at the start of your app, before
> any calls to them are ever made rather than trying to spawn it
> dynamically on first use.

Great this was the sort of advice I needed about potential race conditions.

>        Other than that I can't see any serious problem with it.  I'd
> personally be more inclined to implement something as simple as this
> with an mnesia counter (which can handle both the disc persistence and
> protected get/update operations for you in very few lines of code).

mnesia seemed like a bit of overkill and I was keen to learn from
'first principles' how to ensure synchronous access to the counter
resource.

-- 

Edward Stow



More information about the erlang-questions mailing list