[erlang-questions] example of race conditions ?
Ulf Eliasson
ulf@REDACTED
Tue Jul 31 18:18:24 CEST 2007
Hi,
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()),
loop(as_master);
MasterPid
% Already exist one master, I report in as slave
MasterPid ! {newslave, self()},
loop(as_slave)
end.
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.
Regards,
Ulf
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.
>
> TWINCLING Society
> freedom of innovation
> http://www.twincling.org/
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
--
Ulf Eliasson, ulf@REDACTED
Erlang Training and Consulting
http://www.erlang-consulting.com/
More information about the erlang-questions
mailing list