Skip to content

Commit

Permalink
erlang: add content about concurrency
Browse files Browse the repository at this point in the history
  • Loading branch information
weakish committed May 19, 2014
1 parent 5f49993 commit 93dc62e
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions erlang.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 93dc62e

Please sign in to comment.