在Erlang中,消息发送者可以通过任何方式等待响应吗?

Zub*_*air 9 erlang pid actor

在Erlang中,消息发送者是否可以等待响应,因此只有在处理完消息后才会继续执行?

我的意思是这样的:

Actor ! DoSomething
Continue to this next line of code when DoSomething has been processed
Run Code Online (Sandbox Code Playgroud)

我知道可以通过发送发件人的Pid来进行回调,但还有其他方法可以等待吗?

I G*_*ICE 22

首先要理解的是,Erlang是为处理异步消息传递而构建的.因此,同步消息传递的唯一方法是实现类似于确认的内容.

想象一下两个过程,P1和P2.P1可能会运行以下代码:

%% process P1 takes the Pid of P2 as a parameter
%% and a Message to pass on to P2
p1(P2, Message) ->
    P2 ! {self(), Message},
    receive
        {P2, ok}
    after 5000 -> % this section is optional, times out after 5s
        exit("P2 didn't process this!") % this kills P1
    end.
Run Code Online (Sandbox Code Playgroud)

P2,它可能只运行以下:

p2() ->
    receive
        {From, Message} ->
            io:format("P2 received message ~p~n",[Message]),
            %% processing is done!
            From ! {self(), ok}
    end.
Run Code Online (Sandbox Code Playgroud)

那么你可能会将p2产生为一个新进程.这个将等待任何消息.然后当你调用p1时,它会向P2发送一条消息,然后P2处理它(io:format/2)并回复P1.因为P1正在等待回复,所以在该进程中没有运行其他代码.

这是实现阻塞调用的基本和唯一方法.使用的建议gen_server:call粗略地实现了我刚刚展示的内容.但是它对程序员来说是隐藏的.