[erlang-questions] example of race conditions ?

Ulf Eliasson <>
Tue Jul 31 18:18:24 CEST 2007


The problem is that only one process can have a certain name and what
happens if more then one process want a certain name?

For example, you want to spawn several processes and have one as master
and the rest as slaves.

You do this by having this start function for a module.

start() ->
    % Check if any process is already registered as master
    case whereis(master) of
        undefined ->
            % No master, I register as master and start looping
            register(master, self()),
            % Already exist one master, I report in as slave
            MasterPid ! {newslave, self()},

This will work as long as one process get to execute both whereis and
register without any other processes getting time to execute.

If you now spawn let say ten of these processes, you will likely ending up
with processes checking if master is registered, getting undefined back,
but then some other process execute and register the name, the next time
the first process get to execute it try to register the name master, which
wont work.

A quick and dirty example of a race condition, code is untested and might
contain syntax errors.


On Tue, July 31, 2007 16:59, Saifi Khan wrote:
> Hello:
> The last section in Chap 9 (Errors in Concurrent prog) of
> Programming Erlang book by Dr. Armstrong, says the following:
> "When you combine the Erlang primitives spawn(), spawn_link(),
> register() ..., you must think carefully about possible race
> conditions.
> Write your code in such a way that race conditions cannot happen"
> To me, it seemed like an anti-climax of the whole 'lock free prog'
> model. Please correct me, if I am wrong.
> Can somebody share sample code that *has* race conditions ?
> Appreciate a response from the experienced erlangers.
> thanks
> Saifi.
> freedom of innovation
> http://www.twincling.org/
> _______________________________________________
> erlang-questions mailing list
> http://www.erlang.org/mailman/listinfo/erlang-questions

Ulf Eliasson, 
Erlang Training and Consulting

More information about the erlang-questions mailing list