summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-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