Posted on 14 December 2012

Erlang talk at CWI

I got the invitation to talk at the Programming Environments Meetup at the Centrum for Mathematics and Computer Science (CWI).

The talk was part of a weekly lecture series at the Software Engineering department of the CWI. As an introduction, instead of the obvious Erlang - the Movie video, I started with another one called Erlang - the Ghetto:

The presentation itself is an assemblage of different other Erlang presentations I found on the web. It starts with the language fundamentals and its functional aspects; then continuing onto concurrency and its "Let it crash" philosophy. Then headed on to explain OTP, process supervision and the gen_server. Finally I touched upon performance issues, tuning aspects and common pitfalls.

It was refreshing to give a talk to such skilled people :-)

I illustrated the actor / message passing chapter with the code below: A shell script which processes a number of files in parallel, with limited parallelism and a "worker queue".

#!/usr/bin/escript
%% -*- mode: erlang -*-
main(Files) ->
NumWorkers = 3,
Parent = self(),
Workers = [spawn_link(fun() -> worker(Parent) end) || _ <- lists:seq(1, NumWorkers)],
serve_queue(Files),
%% We need to wait for the workers to finish; with escript, the VM exits when the main process stops
[Worker ! stop || Worker <- Workers],
wait_stop(Workers).
serve_queue([]) ->
ok;
serve_queue([File|Rest]) ->
receive
{want_file, Pid} ->
Pid ! {work, File},
serve_queue(Rest)
end.
wait_stop([]) ->
ok;
wait_stop([_|R]) ->
receive
ok ->
wait_stop(R)
end.
worker(Parent) ->
Parent ! {want_file, self()},
receive
{work, File} ->
resize(File),
worker(Parent);
stop ->
Parent ! ok
end.
resize(F) ->
io:format("Resizing: ~p~n", [F]),
%% os:cmd("mogrify -resize 300x300 " ++ F),
ok.
view raw worker.erl hosted with ❤ by GitHub
Erlang shell script to do some work in parallel on a number of input files. Parallelism is limited by the NumWorkers variable.

Don't use this in production though! This is just meant as a simple shell script demonstrating processes and messaging.

Created on 14 December 2012 12:42, last modified on 14 December 2012 15:19.

Leave a comment