Skip to content

Instantly share code, notes, and snippets.

@mk0x9
Created November 7, 2010 00:02
Show Gist options
  • Save mk0x9/665830 to your computer and use it in GitHub Desktop.
Save mk0x9/665830 to your computer and use it in GitHub Desktop.
%%%
%%% Циркулярный буфер
%%%
%%% Из родительского потока рекурсивно создаем дочерние, дочерние слушают сообщения и передают их потомкам
%%% При создании последнего дочернего потока тот посылает сообщение родителю, и первый дочерний тоже начинает слушать
%%% После получения сообщения, главный родительский посылает последнего дочернему сообщение с указателем на первый дочерний и заканчивает работу
%%%
-module(ring_buffer).
-export([start/2]).
start(N, M) ->
register(parent, self()),
First_Pid = spawn(fun() -> start_child(N-1) end),
loop_parent(First_Pid, N, M).
start_child(0) ->
parent ! {msg, self(), last_thread},
loop_child(0);
start_child(N) ->
Pid = spawn(fun() -> start_child(N-1) end),
loop_child(Pid).
loop_parent(X, K, Threshold) ->
receive
{msg, Pid, last_thread} ->
Pid ! {msg, X, last_thread_ok},
unregister(parent),
Pid ! {msg, pass_me, K*Threshold - 1, Threshold},
io:format("Sent message to last child~n")
end.
loop_child(X) ->
receive
{msg, Pid, last_thread_ok} ->
io:format("I'am last child, got pointer~n"),
loop_child(Pid);
{msg, pass_me, K, Threshold} when K > -1 ->
io:format("I'am ~p, passing message to ~p, ~p left.~n", [self(), X, K]),
X ! {msg, pass_me, K - 1, Threshold},
if
K > Threshold -> loop_child(X);
true -> void
end
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment