Basic "What am I doing wrong?" question (Tuple argument to spawn? Dead pid intead of a runtime error?)

Jonathan Coupe jonathan@REDACTED
Fri Feb 14 18:50:00 CET 2003


I've been spending a mostly pleasant day working through Concurrent
Programming in Erlang, and everything made sense... Until I wrote one of
those horrible programs that you often write while learning a new language,
one that seems to follow every rule you've learned and doesn't provoke as
much as a warning from the compiler, but still doesn't work. And of course
it's almost identical to one that *does* work.

It's a simple variant on progarm 5.2 from Concurrent Programming. The change
is that a tuple is used to contain both the value for the counter and a
name - oh, and I'm registering the counter under that name. An almost
identical program using two separate variables instead the tuple works, this
one doesn't. Instead, start/1 - and spawn - seems to return a pid to a dead
thread. (As far as can tell from the debugger, process_info, and whereis.)

Could someone explain what I've missed, and what behaviour I'm really seeing
here? And why I'm not getting a runtime error?

Thanks

- Jonathan Coupe

----------------------------------------------------------------------------
-------------

-module(ctr).
-export([start/1, loop/1, increment/1, value/1, name/1, stop/1]).


start(Name) ->
 Pid = spawn(counter, loop, [{Name, 0}]),
 register(Name, Pid),
 Pid.


increment(Pid) ->
 Pid ! increment.


value(Pid) ->
 Pid ! {self(), value},
 receive
  {Pid, Value} ->
   Value
 end.


name(Pid) ->
 Pid ! {self(), name},
 receive
  {Pid, Name} ->
   Name
 end.


stop(Pid) ->
 Pid ! stop.


loop({Name,Value}) ->
 receive
  increment ->
   loop({Name, Value+1});
  {From, value} ->
   From ! {self(), Value},
   loop({Name, Value});
  {From, name} ->
   From ! {self(), Name},
   loop({Name, Value});
  stop ->
   true;
  Other ->
   loop({Name, Value})
 end.








More information about the erlang-questions mailing list