【问题标题】:Receive after result not returned结果未返回后接收
【发布时间】:2013-05-09 03:47:59
【问题描述】:

给定一个函数:

%% @doc Retrieves client's state.
-spec(state(pid()) -> atom()).
state(Pid) when is_pid(Pid) ->
  case process_info(Pid) of
    undefined ->
      undefined;
    _Else ->
      Pid ! {state, self()},
      receive
        {state, State} ->
          State
      after
        1000 ->
          undefined
      end
  end.

对于死掉的 pid 和活着的客户端,它可以正常工作:

> client:state(A).
undefined
> client:state(Pid).
online

但是如果进程 Pid 在 1 秒内没有回复他的状态,则由于某种原因返回 Pid:

> client:state(self()).
<0.172.0>

我期待那里有“未定义”的原子。 如何修复此代码?

【问题讨论】:

  • 你为什么期待undefined在这里? process_infoself()返回一些数据,不是未定义的,然后你将{state, self()}发送到self()并接收它。

标签: erlang


【解决方案1】:

发生这种情况是因为您收到了您发送的消息。您的函数在 shell 进程上运行,并向自身发送{state, self()} 消息。发送消息后立即接收消息,函数以State结束,也就是你发送的self() pid。

我希望我没有太混乱。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多