Last active
July 2, 2019 06:03
-
-
Save kaeluka/2cf8cab07c459d39af40 to your computer and use it in GitHub Desktop.
Global mutable state in erlang.
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(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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.