-
-
Save abhi-bit/f837d99f11d8e4f302c1 to your computer and use it in GitHub Desktop.
Receiving messages in gen_server
This file contains hidden or 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(gen_server_msg). | |
-behaviour(gen_server). | |
-export([start/0, msg/1, msg_recv/1]). | |
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). | |
start() -> | |
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). | |
msg(Msg) -> | |
gen_server:call(?MODULE, {msg, Msg}). | |
msg_recv(Msg) -> | |
gen_server:call(?MODULE, {msg_recv, Msg}). | |
init([]) -> | |
{ok, ok}. | |
handle_call({msg, Msg}, _From, ok) -> | |
self() ! {msg2, Msg}, | |
{reply, ok, ok}; | |
handle_call({msg_recv, Msg}, _From, ok) -> | |
eprof:start(), | |
eprof:start_profiling([erlang:whereis(cb_set_view)]), | |
AllowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", | |
get_random_string(1024000, AllowedChars), | |
self() ! {msg2, Msg}, | |
receive | |
{msg2, Msg} -> | |
io:format("Received the message `~s` directly.~n", [Msg]) | |
after 0 -> | |
io:format("Didn't receive the message `~s` directly.~n", [Msg]) | |
end, | |
eprof:stop_profiling(), | |
eprof:log("/tmp/profile.log"), | |
eprof:analyze(total), | |
{reply, ok, ok}. | |
handle_cast(__, ok) -> | |
{noreply, ok}. | |
handle_info({msg2, Msg}, ok) -> | |
io:format("Received the message `~s` in handle_info.~n", [Msg]), | |
{noreply, ok}. | |
terminate(_, ok) -> | |
ok. | |
code_change(_, ok, _) -> | |
{ok, ok}. | |
get_random_string(Length, AllowedChars) -> | |
lists:foldl(fun(_, Acc) -> | |
[lists:nth(random:uniform(length(AllowedChars)), | |
AllowedChars)] ++ Acc | |
end, [], lists:seq(1, Length)). | |
This file contains hidden or 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
$ erl ~/src/erlang/misc | |
Erlang R16B03-1 (erts-5.10.4.0.0.1) [source-62b74b5] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] | |
Eshell V5.10.4.0.0.1 (abort with ^G) | |
1> gen_server_msg:start(). | |
{ok,<0.35.0>} | |
2> gen_server_msg:msg("Hello World"). | |
Received the message `Hello World` in handle_info. | |
ok | |
3> gen_server_msg:msg_recv("Hello World"). | |
Received the message `Hello World` directly. | |
ok |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment