`receive after`和`timer:sleep`之间有什么区别吗?

时间:2015-11-23 08:24:17

标签: erlang

timer:sleep的实施是:

-spec sleep(Time) -> 'ok' when
  Time :: timeout().
sleep(T) ->
    receive
    after T -> ok
    end.

所以timer:sleep等于这段代码:

receive ->
    never_match -> %% note: this never to be matched
        ok 
    after 1000
        ok
end.

我想知道:

  1. timer:sleep sleepingblocking的流程状态是什么?

  2. 对于Erlang VM进程调度,此实现有什么不同吗?

1 个答案:

答案 0 :(得分:4)

timer:sleep/1和硬编码receive...after...end声明之间没有区别(怎么可能?后者是后者defined

此外,根据process_info/1的文档,流程'状态可以是:

Status :: exiting
        | garbage_collecting
        | waiting
        | running
        | runnable
        | suspended

在这两种情况下(timerreceive...),流程均为waiting

4> spawn(fun() -> receive after 5000 -> ok end end).
<0.40.0>
5> process_info(v(4), status).                      
{status,waiting}
6> spawn(fun() -> timer:sleep(5000) end).           
<0.43.0>
7> process_info(v(6), status).           
{status,waiting}