user1002288
user1002288

Reputation: 5040

multiprocess program running in Erlang currency programming

I am trying to learn Erlang currency programming.

This is an example program got from Erlang.org but no instructions about how to run it.

I run it in this way,

1> counter:start() 
<0.33.0>

But, I do not know how to run other functions so that the process (counter:start()) can do the work according to the received message.

How to confirm that two or more processes have really been generated ?

Another question, how to print out received message in a function ?

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

 %% First the interface functions.
 start() ->
       spawn(counter, loop, [0]).

 increment(Counter) ->
       Counter ! increment.

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

%% The counter loop.
 loop(Val) ->
    receive
            increment ->
                    loop(Val + 1);
            {From,value} ->
                    From ! {self(),Val},
                    loop(Val);
            stop -> % No recursive call here
                    true;
            Other -> % All other messages
                    loop(Val)
    end.

Any help will be appreciated.

thanks

Upvotes: 0

Views: 213

Answers (2)

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91902

Other functions will just use the module you just created, like this:

C = counter:start(),
counter:increment(C),
counter:increment(C),
io:format("Value: ~p~n", [counter:value(C)]).

You can run pman:start() to bring up the (GUI) process manager to see which processes you have.

Upvotes: 2

Roberto Aloi
Roberto Aloi

Reputation: 30985

In addition to what Emil said, you can use the i() command to verify which processes are running. Let's start three counters:

1> counter:start().
<0.33.0>
2> counter:start().
<0.35.0>
3> counter:start().
<0.37.0>

And run i():

...
<0.33.0>              counter:loop/1                         233        1    0
                      counter:loop/1                           2              
<0.35.0>              counter:loop/1                         233        1    0
                      counter:loop/1                           2              
<0.37.0>              counter:loop/1                         233        1    0
                      counter:loop/1                           2              
...

As you can see, the above processes (33, 35 and 37) are happily running and they're executing the counter:loop/1 function. Let's stop process 37:

4> P37 = pid(0,37,0).
<0.37.0>
5> counter:stop(P37).
stop

Checking the new list of processes:

6> i().

You should verify it's gone.

Upvotes: 2

Related Questions