Skip to content

Instantly share code, notes, and snippets.

@bluegraybox
Created August 25, 2012 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluegraybox/3470477 to your computer and use it in GitHub Desktop.
Save bluegraybox/3470477 to your computer and use it in GitHub Desktop.
Cheat sheet for Erlang IPC syntax & functions
-module(cheat_sheet_ipc).
-export([init/0, incr/1, decr/1, current/0]). % not loop/0
%% Define a constant.
-define(SVC_NAME, counter_service). % atom, not Variable or string
%% Start a new process to manage our counter.
init() ->
%% MyFunc is a reference to a function
MyFunc = fun () -> % could all be on one line
loop(0)
end,
%% Start a new process running MyFunc.
Pid = spawn(MyFunc), % pass the function reference; don't invoke it here.
%% Register the Pid, so we can send it messages by name.
register(?SVC_NAME, Pid).
%% Our message handling loop - not visible outside this module
loop(Current) ->
NewCurrent = receive % blocks until a new message comes in.
{incr, Count} -> Current + Count; % no response
{decr, Count} -> Current - Count;
{current, Pid} ->
Pid ! {ok, Current}, % send the response
Current; % Return value so NewCurrent gets set
Invalid -> % catch everything else
io:format("Invalid message: ~p~n", [Invalid]),
Current
end,
loop(NewCurrent). % tail-recurse with updated value
%% Wrapper functions for asynchronous sends.
incr(Count) -> ?SVC_NAME ! {incr, Count}.
decr(Count) -> ?SVC_NAME ! {decr, Count}.
%% Wrap async send/receive as synchronous function.
current() ->
%% Send a message and wait for a response.
?SVC_NAME ! {current, self()},
receive
{ok, Current} ->
io:format("Current value=~B~n", [Current])
end.
@bluegraybox
Copy link
Author

$ erl
Erlang R15B01 (erts-5.9.1) [source] [64-bit] [smp:4:4] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9.1 (abort with ^G)
1> c(cheat_sheet_ipc).
{ok,cheat_sheet_ipc}
2> cheat_sheet_ipc:init().
true
3> cheat_sheet_ipc:current().
Current value=0
ok
4> cheat_sheet_ipc:incr(5).
{incr,5}
5> cheat_sheet_ipc:current().
Current value=5
ok
6> cheat_sheet_ipc:decr(2).
{decr,2}
7> cheat_sheet_ipc:current().
Current value=3
ok
8>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment