Erlang接收消息并打印该消息

z0qdvdin  于 2022-12-16  发布在  Erlang
关注(0)|答案(1)|浏览(198)
-module(cooperate).
-compile(export_all).

producer(_Pid, 0) ->
    done;
producer(Pid, N) -> 
    Pid ! {producer, N},
    io:format("process ~p producing ~p~n", [self(), rand:uniform(N)]),
    producer(Pid, N-1).

consumer() ->
    receive
        {producer,Pid} ->
            timer:sleep(10),io:format("process ~p consuming ~p~n", [self(), Pid]),
            consumer()
        after 40 ->
            stopping_terminus
        end.

go() ->
    Pid = spawn(cooperate, consumer, []),
    spawn(cooperate, producer, [Pid, 3]).

Expecting:

process <x.xx.x> producing 2
process <x.xx.x> producing 100
process <x.xx.x> producing 555
process <x.xx.x> consuming 2
process <x.xx.x> consuming 100
process <x.xx.x> consuming 555

我成功地产生了随机数,如2,100,555。现在,我想把消息发送给消费者并打印出来。通过上面的代码,我只能打印消费者3,2,1,因为生产者(Pid,N-1)。

vjrehmav

vjrehmav1#

此行:

Pid ! {producer, N},

将消息{producer, N}发送给使用者。例如,使用者将收到类似{producer, 3}的消息。您应该注意,在使用者的receive语句中:

receive
    {producer,Pid} ->


Pid不会与pid匹配。仅仅因为您将变量命名为Pid,并不意味着它实际上会与pid匹配。在erlang中,pid是它自己的类型--它不是整数。pid在shell中打印时如下所示:

<0.83.0>

在receive中,Pid实际上与N匹配,并且N不是一个pid,而N只是一个作为参数传递的整数。不要命名与pid不匹配的变量Pid
如果你想让生产者发送一个随机数给消费者,你会怎么做呢?你需要生产者发送一个类似{producer, SomeRandomNumber}的消息,你会怎么做呢?

Pid ! {producer, SomeRandomNumber}

如果使用者需要区分包含N的消息和包含SomeRandomNumber的消息,则可以按如下方式发送消息:

Pid ! {producer, producer_id, N}
Pid ! {producer, rand_num, SomeRandomNumber}

(甚至Pid ! {producer, N, SomeRandomNumber}
然后,在使用者的receive语句中,可以使用匹配对使用者接收到的不同类型的消息执行不同的操作:

receive
    {producer, producer_id, N} ->
        io:format("consumer ~p received message from producer ~p~n", [self(), N]),
        consumer();
    {producer, rand_num, SomeRandomNumber} ->
        io:format("consumer ~p got random number ~p~n", [self(), SomeRandomNumber]),
        consumer()
after 40 ->
    stopping_terminus
end.

相关问题