Chinaunix首页 | 论坛 | 博客
  • 博客访问: 752902
  • 博文数量: 130
  • 博客积分: 2951
  • 博客等级: 少校
  • 技术积分: 1875
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-04 18:32
文章分类

全部博文(130)

文章存档

2013年(1)

2012年(129)

分类: Python/Ruby

2012-03-02 18:27:53

The Erlang BIF spawn is used to create a new process: spawn(Module, Exported_Function, List of Arguments)

  1. -module(tut15).

  2. -export([start/0, ping/2, pong/0]).

  3. ping(0, Pong_PID) ->
  4.     Pong_PID ! finished,
  5.     io:format("ping finished~n", []);

  6. ping(N, Pong_PID) ->
  7.     Pong_PID ! {ping, self()},
  8.     receive
  9.         pong ->
  10.             io:format("Ping received pong~n", [])
  11.     end,
  12.     ping(N - 1, Pong_PID).

  13. pong() ->
  14.     receive
  15.         finished ->
  16.             io:format("Pong finished~n", []);
  17.         {ping, Ping_PID} ->
  18.             io:format("Pong received ping~n", []),
  19.             Ping_PID ! pong,
  20.             pong()
  21.     end. %Note: no ";" before the end.

  22. start() ->
  23.     Pong_PID = spawn(tut15, pong, []),
  24.     spawn(tut15, ping, [3, Pong_PID]).

输出:
  1. 1> c(tut15).
  2. {ok,tut15}
  3. 2> tut15: start().
  4. <0.36.0>
  5. Pong received ping
  6. Ping received pong
  7. Pong received ping
  8. Ping received pong
  9. Pong received ping
  10. Ping received pong
  11. ping finished
  12. Pong finished

阅读(974) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~