Skip to content

Instantly share code, notes, and snippets.

@kaeluka kaeluka/horr.erl
Last active Jul 2, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.