Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kaeluka
Last active July 2, 2019 06:03
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaeluka/2cf8cab07c459d39af40 to your computer and use it in GitHub Desktop.
Save kaeluka/2cf8cab07c459d39af40 to your computer and use it in GitHub Desktop.
Global mutable state in erlang.
-module(horr).
-export([malloc/0, free/1, read/1, write/2, test/0]).
% You can use `malloc` to get a globally sharable, mutable cell of memory.
% A difference to C's `malloc` is that such a cell doesn't have a certain size (you can't overflow)
% Memory is initialised with the atom `null`.
malloc() ->
spawn(fun() -> mem(null) end).
% As processes are not garbage collected, you have to call `free` when you're done with your memory:
free(Mem) ->
Mem ! free.
% Read from memory:
read(Mem) ->
Mem ! {read, self()},
receive
{reply, Val} ->
Val
end.
% Write to memory:
write(Val, Mem) ->
Mem ! {write, self(), Val},
receive ack -> ok end.
mem(Val) ->
receive
{read, Pid} ->
Pid ! {reply, Val},
mem(Val);
{write, Pid, NewVal} ->
Pid ! ack,
mem(NewVal);
free -> ok
end.
test() ->
Ptr = malloc(),
case read(Ptr) of
null -> ok;
_ -> throw("not initialised properly")
end,
write(10, Ptr),
case read(Ptr) of
10 -> ok;
_ -> throw("not set properly")
end,
case read(Ptr) of
10 -> ok;
_ -> throw("not set properly")
end.
@maplant
Copy link

maplant commented Aug 13, 2014

I like this, it reminds me of the time I created a small "mem" lib as an experiment - it essentially just provided an infinite, mutable array via processes.

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