Erlang 的 spawn() 使用时,值得注意的一点

来源:互联网 发布:java 线程池 名字关闭 编辑:程序博客网 时间:2024/06/18 10:43
spawn() 在使用的过程中遇到一个有趣的事儿,描述如下:
A:    spawn(fun() -> io:format("hello world~n", []) end),
B:    spawn(out_put()).
以上两种方式的处理方式不同。
区别在于: A 直接返回 进程ID    而B 知道 out_put()结束才返回进程ID。

实例:
情况A:
-module(spawn_test).

-export([start/0]).
-export([out_time/1]).

out_time(0) ->
        io:format("GAME OVER~n", []);
out_time(N) ->
        receive after
                1000 ->
                        io:format("the time is ~p~n", [erlang:now()])
        end,
        out_time(N - 1).

start() ->
        io:format("start to run:~n", []),
        Ret = spawn(fun() -> out_time(10) end),
        io:format("return_value is ~p I am return, I am function.Just now is ~p~n", [Ret, erlang:now()]),
        spawn(fun() -> io:format("I am fun, I am running.You are wrong.~n", []) end).
结果是:

情况B:
-module(spawn_test).

-export([start/0]).
-export([out_time/1]).

out_time(0) ->
        io:format("GAME OVER~n", []);
out_time(N) ->
        receive after
                1000 ->
                        io:format("the time is ~p~n", [erlang:now()])
        end,
        out_time(N - 1).

start() ->
        io:format("start to run:~n", []),
        Ret = spawn(?MODULE, out_time, [10]),
        io:format("return_value is ~p I am return, I am function.Just now is ~p~n", [Ret, erlang:now()]),
        spawn(fun() -> io:format("I am fun, I am running.You are wrong.~n", []) end).

0 0