Skip to content

Instantly share code, notes, and snippets.

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

What would you like to do?
Global mutable state in erlang.
-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()},
{reply, Val} ->
% Write to memory:
write(Val, Mem) ->
Mem ! {write, self(), Val},
receive ack -> ok end.
mem(Val) ->
{read, Pid} ->
Pid ! {reply, Val},
{write, Pid, NewVal} ->
Pid ! ack,
free -> ok
test() ->
Ptr = malloc(),
case read(Ptr) of
null -> ok;
_ -> throw("not initialised properly")
write(10, Ptr),
case read(Ptr) of
10 -> ok;
_ -> throw("not set properly")
case read(Ptr) of
10 -> ok;
_ -> throw("not set properly")

This comment has been minimized.

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