Shared memory
Two programs on one computer can use the same block of memory. This lesson creates a named memory-mapped file, writes numbers and text into it, lets a second copy of the program read and answer, and edits a file in place through a mapping.
What you will learn#
- what a memory-mapped file is,
MemoryMappedFile.CreateNewandOpenExisting(a named block that two programs share),- a view accessor for numbers (
Write,ReadInt32,ReadDouble) and a view stream for text, - why a text read from the memory ends at the first zero byte,
- mapping a real file (
CreateFromFile) and changing it in place.
The idea#
A normal file is read and written through calls. A memory-mapped file is a file (or just a block of memory with a name) that the system shows to your program as ordinary memory: what one program writes into it, another program that mapped the same name sees at once. It is the fastest way for programs on one computer to share data, and it is also a comfortable way to work with a very big file without loading it.
Compare the tools of the last tutorials: a named pipe (the tutorial Two programs talking) sends messages one after another; shared memory is a place both programs can read and write at any time.
The program#
# shared memory - a memory-mapped file seen by two programs, numbers and text in it, and a file that is edited in place
# ring ch06_shared_memory.ring the parent: it makes the memory and starts the child
# ring ch06_shared_memory.ring --child the child (the parent starts it)
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Diagnostics"
"System.IO.MemoryMappedFiles"
"System.Threading"
}
C_NAME = "ringdotnet_shared_memory"
func main
if find(sysargv,"--child") > 0
runChild()
return
ok
# a NAMED memory map is a Windows feature (on Linux and macOS .NET maps files only); the file part runs everywhere
if isWindows()
runParent()
else
? "Named shared memory is available on Windows only; this part is skipped."
ok
editFileInPlace()
# ---------------------------------------------------------------- two programs, one block of memory
func runParent
# A memory-mapped file is a block of memory with a NAME. Any program of this computer that knows the name can open it.
oMap = new MemoryMappedFile().CreateNew([ :mapName = C_NAME, :capacity = 4096 ])
oAccessor = oMap.CreateViewAccessor(NULL) # a view with Read and Write methods at a position (in bytes)
# 1. Numbers: Write(position, value) and ReadInt32(position), ReadDouble(position). A whole Ring number is written as 4 bytes
# (an int), a number with decimals as 8 bytes (a double). The positions are chosen by us: 0 = the first number, 4 = the second...
oAccessor.Write(0,21)
oAccessor.Write(8,3.5)
? "1. the parent wrote the int 21 at position 0 and the double 3.5 at position 8"
# 2. Text: a stream on the memory (CreateViewStream) works with StreamWriter and StreamReader like a file does. The text starts at 100.
# (The memory is zero-filled, so a reader sees the text and then zeros: the reading side cuts the text at the first zero byte.)
oStream = oMap.CreateViewStream([ :offset = 100, :size = 200 ])
oWriter = new StreamWriter(oStream)
oWriter.Write("Hello from the parent")
oWriter.Flush()
oStream.Dispose()
? "2. the parent wrote a text at position 100"
# 3. Start the child and read what it prints. It finds the memory by its name, reads the numbers and the text, and answers in the same memory.
oInfo = new ProcessStartInfo().@New([ :fileName = exefilename(), :arguments = '"' + filename() + '" --child' ])
oInfo {
UseShellExecute = False
CreateNoWindow = True
RedirectStandardOutput = True
}
oChild = new Process().Start(oInfo)
cOutput = oChild.StandardOutput.ReadToEnd()
oChild.WaitForExit(NULL)
? nl + "3. the child says:"
? " " + substr(chomp(cOutput),char(10),nl + " ")
# 4. The answer of the child is in the same memory: read it from the positions that were agreed
? nl + "4. the answer of the child at position 4 (21 * 2): " + oAccessor.ReadInt32(4)
oAnswer = oMap.CreateViewStream([ :offset = 300, :size = 200 ])
cAnswer = textOf(new StreamReader(oAnswer).ReadLine())
? " the text of the child at position 300: " + cAnswer
oAccessor.Dispose()
oMap.Dispose()
func runChild
oMap = new MemoryMappedFile().OpenExisting(C_NAME) # open: the parent made it
oAccessor = oMap.CreateViewAccessor(NULL)
nNumber = oAccessor.ReadInt32(0)
nDecimal = oAccessor.ReadDouble(8)
oStream = oMap.CreateViewStream([ :offset = 100, :size = 200 ])
cText = textOf(new StreamReader(oStream).ReadLine())
? "I read the int " + nNumber + ", the double " + nDecimal
? "and the text '" + cText + "'"
oAccessor.Write(4,nNumber * 2)
oAnswer = oMap.CreateViewStream([ :offset = 300, :size = 200 ])
oWriter = new StreamWriter(oAnswer)
oWriter.Write("Hello from the child")
oWriter.Flush()
# ---------------------------------------------------------------- a file edited in place
func editFileInPlace
# 5. Map a FILE: the view is the content of the file, and a change in memory is a change in the file. Nothing is read or written
# by you: the system moves the data. The program changes the second of three numbers in a file without touching the others.
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_shared_memory.bin"])
oConverter = new BitConverter()
new File().WriteAllBytes(cFile,oConverter.GetBytes(10) + oConverter.GetBytes(20) + oConverter.GetBytes(30))
oMap = new MemoryMappedFile().CreateFromFile(cFile)
oAccessor = oMap.CreateViewAccessor(NULL)
nOld = oAccessor.ReadInt32(4)
oAccessor.Write(4,99)
oAccessor.Flush()
oAccessor.Dispose()
oMap.Dispose()
cBytes = new File().ReadAllBytes(cFile)
? nl + "5. a file of " + len(cBytes) + " bytes: the second number was " + nOld + ", now it is " + oConverter.ToInt32(cBytes,4) + "; the first is " + oConverter.ToInt32(cBytes,0) + " and the third " + oConverter.ToInt32(cBytes,8)
new File().Delete(cFile)
# the memory is filled with zero bytes: a text ends at the first one
func textOf cText
nZero = substr(cText,char(0))
if nZero > 0
return left(cText,nZero - 1)
ok
return cText
func chomp cText
while right(cText,1) = char(10) or right(cText,1) = char(13)
cText = left(cText,len(cText) - 1)
end
return cText1. the parent wrote the int 21 at position 0 and the double 3.5 at position 8
2. the parent wrote a text at position 100
3. the child says:
I read the int 21, the double 3.50
and the text 'Hello from the parent'
4. the answer of the child at position 4 (21 * 2): 42
the text of the child at position 300: Hello from the child
5. a file of 12 bytes: the second number was 20, now it is 99; the first is 10 and the third 30A memory-mapped file with a name (the first part of the program) is a Windows feature. On Linux and macOS .NET maps files only, so the program prints a message and runs the last part, the file edited in place.
How it works#
One name, two programs#
The parent calls MemoryMappedFile.CreateNew([ :mapName = "...", :capacity = 4096 ]): a block of 4,096 bytes with a name. The child (a second copy of the same program, started with --child as in Two programs talking) calls OpenExisting(name) and gets the same block. Nothing is copied.
Numbers#
CreateViewAccessor(NULL) gives a view with methods that work at a position (a byte number): Write(position, value), ReadInt32(position), ReadDouble(position), ReadBoolean(position). The two programs must agree on the layout — here: position 0 holds an integer, position 4 the answer, position 8 a number with decimals. A whole Ring number is written as 4 bytes (an int), a number with decimals as 8 bytes (a double); read it back with the matching Read… method.
Write takes the type from the value you give it. Because every whole Ring number is written as an int, the accessor in this lesson stores integers and doubles only; for single bytes or other types use a BinaryWriter on a view stream.
Text#
CreateViewStream([ :offset = 100, :size = 200 ]) is a Stream over a part of the memory, so StreamWriter and StreamReader work on it exactly like on a file (the tutorial Streams and compression). The memory starts filled with zero bytes: a reader that reads the whole view sees the text and then zeros, so textOf cuts the text at the first zero byte. If you design a protocol on shared memory, store the length first, or end texts with a zero.
The conversation#
Parent: writes the numbers and the text, starts the child and reads its output. Child: opens the memory, reads, writes 21 × 2 at position 4 and a text at position 300. Parent: reads both after the child ended. In a real program the two programs would run at the same time, so they need a way to say "my data is ready": a flag in the memory that the other side polls, or a named mutex or event (the tutorial Two programs talking).
A file edited in place#
CreateFromFile(path) maps a real file. The view is the content of the file: Write(4, 99) changes four bytes of the file at position 4, and Flush() makes sure that the system writes the change. The program reads the file again with ReadAllBytes and shows that only the second of the three numbers changed. BitConverter.GetBytes(10) makes the four bytes of a number and ToInt32(bytes, position) reads one back.
This is the usual way to patch a large file, to read a huge file piece by piece, or to keep a database file that several programs use.
Two programs that write the same place at the same time can destroy each other's data. Decide who writes where, or use a lock (a Mutex) around the writes.
What you learned#
- named shared memory and
OpenExisting, CreateViewAccessorfor numbers andCreateViewStreamfor text,- zero-filled memory and cutting a text,
CreateFromFilefor editing a file in place,- the need for a layout and for locking.
Exercises#
- Put a "ready" flag at position 200 and let the child wait (
Thread.Sleepin a loop) until the parent sets it. - Keep a counter at position 0 that both programs increase, protected by a
Mutex. - Map a text file and replace one character of it in place.
- Store a text as length first: four bytes for the length, then the text.