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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值