Skip to content

Instantly share code, notes, and snippets.

@nicolasff
Created January 13, 2009 13:12
Show Gist options
  • Save nicolasff/46439 to your computer and use it in GitHub Desktop.
Save nicolasff/46439 to your computer and use it in GitHub Desktop.
-module(counter_with_retry).
-compile(export_all).
start_counter() ->
Pid = spawn(?MODULE, counter_loop, [0]),
register(counter, Pid).
counter_loop(N) ->
receive
{get, Pid} ->
Pid ! {value, N},
counter_loop(N);
{set, Pid, N, New} ->
Pid ! ok,
counter_loop(New);
{set, Pid, _Something, _New} ->
Pid ! fail,
counter_loop(N);
value -> io:format("Value = ~w~n", [N])
end.
counter_locked(Pid, N) ->
receive
{inc, Pid} -> counter_locked(Pid, N+1);
{unlock, Pid} -> counter_loop(N)
end.
proc() ->
Pid = self(),
counter ! {get, Pid},
receive
{value, N} ->
counter ! {set, Pid, N, N + 1},
receive fail -> proc(); % retry
ok -> wait_death()
end
end.
wait_death() ->
receive
{halt, Parent} -> Parent ! {halted, self()}
end.
sync([]) -> ok;
sync([Pid|Pids]) ->
Pid ! {halt, self()},
receive
{halted, Pid} -> sync(Pids)
end.
run() ->
start_counter(),
N = lists:seq(1, 10000),
Pids = lists:map(fun(_) -> spawn(?MODULE, proc, []) end, N),
sync(Pids),
counter ! value,
ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment