Posts Tagged ‘example’
Introduction to Erlang : Shared Memory Example
Shared Memory
This post will be about building step by step a shared memory abstraction in Erlang. As you should all know, variables in Erlang are immutable; once a variable is bound to a value, this value cannot change. Thus in order to implement a mutable variable/object we need to represent it with a recursive process responsible for keeping the current value and providing the interface for using the object (read and write operations for example).
So, in order to implement a memory abstraction we have to use the aforementioned approach. We can either create a single process to be responsible for keeping the whole address space as a simple list, or create one process for each allocation operation. We will follow the second approach because it is more interesting and protects the memory process from becoming the bottleneck.
Let’s start!
The Messaging Interface
The interface of the memory system is quite simple. We just need the following operations:
start
: for starting the memory systemstop
: for stopping the memory systemalloc
: for allocating memoryfree
: for freeing memoryread
: for reading the value of a memory addresswrite
: for writing to a memory address
From the above, the four first operations will be handled by the memory system, while the two last by each memory address (process) that they refer to. We will create two modules:
mem
: the memory systemmemif
: the memory interface
and one file called “common” with the parameters of the system.
-define(MEMREGNAME, mem). -define(MAXSIZE, 100). |
This file will be include in both other modules (-include("common")
directive).
Read the rest of this entry »