Created
April 24, 2017 02:25
-
-
Save grantwinney/171dd03b6db6c8dd557fad79a8971c39 to your computer and use it in GitHub Desktop.
Small example of scaling up processes to handle an increased workload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(scaling). | |
-export([start_router/0, init_router/0, process_message/1]). | |
-define(MESSAGE_LIMIT, 3). | |
start_router() -> | |
register(scaling, spawn(scaling, init_router, [])). | |
init_router() -> | |
process_flag(trap_exit, true), | |
loop(). | |
loop() -> | |
receive | |
{messages, Messages} -> | |
io:format("Generating ~p processes to handle ~p incoming messages.~n", | |
[(length(Messages) + ?MESSAGE_LIMIT - 1) div ?MESSAGE_LIMIT, length(Messages)]), | |
spawn_message_handlers(Messages), | |
loop(); | |
{quit, Reason} -> | |
io:format("The server and linked processes will now quit. Reason: ~p~n", [Reason]); | |
{'EXIT', Pid, Reason} -> | |
io:format("Received EXIT signal from ~p: ~p~n", [Pid, Reason]), | |
loop() | |
end. | |
spawn_message_handlers([]) -> | |
ok; | |
spawn_message_handlers(AllMessages) when length(AllMessages) =< ?MESSAGE_LIMIT -> | |
spawn_link(scaling, process_message, [AllMessages]); | |
spawn_message_handlers(AllMessages) -> | |
{Messages, RestOfMessages} = lists:split(?MESSAGE_LIMIT, AllMessages), | |
spawn_link(scaling, process_message, [Messages]), | |
spawn_message_handlers(RestOfMessages). | |
process_message(Messages) -> | |
lists:foreach(fun(Message) -> | |
io:format("Process ~p handling message: ~p~n", [self(), Message]) | |
end, Messages). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment