%%% $Id: prodcons.erlang,v 1.0 2002/10/21 16:58:00 dada Exp $
%%% http://dada.perl.it/shootout
%%%
%%% contributed by James Hague

-module(prodcons).
-export([main/0, main/1, producer/2, consumer/1]).

main() -> main(['1']).
main([Arg]) ->
    N = list_to_integer(atom_to_list(Arg)),
    spawn(prodcons, producer, [self(), N]),
    receive
        {Produced, Consumed} ->
            io:fwrite("~w ~w~n", [Produced, Consumed]),
            halt(0)
    end.

producer(From, N) ->
    Result = producer_loop(spawn(prodcons, consumer, [0]), 0, N),
    From ! Result.

producer_loop(Consumer, Produced, 0) ->
    Consumer ! {self(), stop},
    receive
        Consumed -> {Produced, Consumed}
    end;
producer_loop(Consumer, Produced, N) ->
    Consumer ! {self(), N},
    receive
        ok -> producer_loop(Consumer, Produced + 1, N - 1)
    end.

consumer(Consumed) ->
    receive
        {From, stop} ->
            From ! Consumed;
        {From, I} ->
            From ! ok,
            consumer(Consumed + 1)
    end.