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

david wallin david.wallin@REDACTED
Fri Feb 14 19:20:59 CET 2003


Hi Jonathan,

Well, one thing is that  you call this module 'ctr' but spawn calls a  
module name 'counter'.
You could use '?MODULE' instead:

spawn(?MODULE, loop, [{Name, 0}])

saves you headache when you rename modules.

cheers,

--david.

On Friday, February 14, 2003, at 05:50 PM, Jonathan Coupe wrote:

> 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