summaryrefslogtreecommitdiffhomepage
path: root/erlang.html.markdown
diff options
context:
space:
mode:
authorJakukyo Friel <weakish@gmail.com>2014-05-19 15:31:09 +0800
committerJakukyo Friel <weakish@gmail.com>2014-05-19 15:31:09 +0800
commit93dc62e0a32c3915f4242248dcb698b72083dd41 (patch)
tree03b701292091e7c044e057f7da10738cdee09bb3 /erlang.html.markdown
parent5f49993e555109aa17468e8a2e900f6079d7db54 (diff)
erlang: add content about concurrency
Diffstat (limited to 'erlang.html.markdown')
-rw-r--r--erlang.html.markdown39
1 files changed, 39 insertions, 0 deletions
diff --git a/erlang.html.markdown b/erlang.html.markdown
index 065219ba..64b62f05 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -241,6 +241,45 @@ catcher(N) ->
% exception, it is converted into a tuple that describes the error.
catcher(N) -> catch generate_exception(N).
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% 4. Concurrency
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Erlang relies on the actor model for concurrency. All we need to write
+% concurrent programs in erlang are three primitives: spawning processes,
+% sending messages and receiving messages.
+
+% To start a new process we use the `spawn` function, which takes a function
+% as argument.
+
+F = fun() -> 2 + 2 end. % #Fun<erl_eval.20.67289768>
+spawn(F). % <0.44.0>
+
+% `spawn` returns a pid (process identifier), you can use this pid to send
+% messages to the process. To do message passing we use the `!` operator.
+% For all of this to be useful we need to be able to receive messages. This is
+% achieved with the `receive` mechanism:
+
+-module(caculateGeometry).
+-compile(export_all).
+caculateAera() ->
+ receive
+ {rectangle, W, H} ->
+ W * H;
+ {circle, R} ->
+ 3.14 * R * R;
+ _ ->
+ io:format("We can only caculate area of rectangles or circles.")
+ end.
+
+% Compile the module and create a process that evaluates `caculateAera` in the shell
+c(caculateGeometry).
+CaculateAera = spawn(caculateGeometry, caculateAera, []).
+CaculateAera ! {circle, 2}. % 12.56000000000000049738
+
+% The shell is also a process, you can use `self` to get the current pid
+self(). % <0.41.0>
+
```
## References