Skip to content

Instantly share code, notes, and snippets.

@nicolasff
Created January 13, 2009 12:50
Show Gist options
  • Save nicolasff/46434 to your computer and use it in GitHub Desktop.
Save nicolasff/46434 to your computer and use it in GitHub Desktop.
-module(counter_with_locks).
-compile(export_all).
start_counter() ->
Pid = spawn(?MODULE, counter_loop, [0]),
register(counter, Pid).
counter_loop(N) ->
receive
{lock, Pid} -> counter_locked(Pid, 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 ! {lock, Pid},
counter ! {inc, Pid},
counter ! {unlock, Pid},
receive
{halt, Parent} -> Parent ! {halted, Pid}
end.
sync([]) -> ok;
sync([Pid|Pids]) ->
Pid ! {halt, self()},
receive
{halted, Pid} -> sync(Pids)
end.
run() ->
start_counter(),
N = lists:seq(1, 1000000),
Pids = lists:map(fun(_) -> spawn(fun proc/0) 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