[erlang-questions] Question regarding problems in Joe's book

Mike Berrow <>
Sat Jul 28 05:54:33 CEST 2007


> .....  but I wonder if anyone knows if there are answers posted 
> for the problems at the end of section 8? I've been struggling with 
> working out these problems and am looking to learn from an example. 

I wondered the same thing. The first problem seems simple, but I am not
sure how to prove that it works when "two  parallel processes simultaneously evaluate start/2"

Anyway, here is my attempt so far (and a session transcript)

% Write a function start(AnAtom, Fun) to register AnAtom as spawn(Fun).
% Make sure your program works correctly in the case when two
% parallel processes simultaneously evaluate start/2. In this case,
% you must guarantee that one of these processes succeeds and the
% other fails.
-module(sfun).
-export([start/2]).

start(AnAtom, Fun) -> 
  case whereis(AnAtom) of
    undefined -> register(AnAtom, spawn(Fun)), succeed;
    _Else -> fail
    %_Else -> throw(already_started)
  end.

% 1> c(sfun).
% {ok,sfun}
% 2> sfun:start(area0, fun area_server0:loop/0).
% succeed
% 3> area0 ! {rectangle, 4, 15}.
% Area of rectangle is 60
% {rectangle,4,15}
% 4> area0 ! {rectangle, 4, 20}.
% Area of rectangle is 80
% {rectangle,4,20}
% 5> sfun:start(area0, fun area_server0:loop/0).
% fail
% 6> sfun:start(area1, fun area_server1:loop/0).
% succeed
% 7> area1 ! {rectangle, 4, 30}.
% {rectangle,4,30}
% 8> sfun:start(area1, fun area_server1:loop/0).
% fail

As for the second problem, the "ring benchmark".
I've dug up (around the net) 4 different apparent solutions to that, but they all 
produce very different timings. If there is interest, I can post what I found here.
I rather felt "thrown into the deep end" on that one,

-- Mike Berrow







More information about the erlang-questions mailing list