C++ – How to Increase the Size of a Memory Mapped File

cfilesmemory

I am maintaning a memory mapped file to store my tree like datastructure.

When I'm updating the datastructure ,I got this problem.
The file is limited on it's size and can't be too long or too small.

I have a methods like

 void mapfile_insert_record(RECORD* /* record*/);

 void mapfile_modify_record(RECORD* /* record*/);

Both operations could lead to exceed the space which is free on memory file.

How do I overcome this?
What strategy I should use.

  1. calculate whether it requires to exceed the file as a pre-condition on both
    methods.
  2. Dynamically exceed it , for a example manage a timer and constantly polling file
    for it's free avaliable size and then automatically extend it.

Any ideas or patterns to overcome this problem?

Best Answer

Polling is not a good idea. It would only makes sense if the file is modified by other processes but even then it is better to extend only before insert/modify. Besides, concurrent access is dangerous, as you have to worry about synchronization.

Assuming that your file is never shrunk, you can cache the size of the file, so you only have to check the file size if your current request is outside of the last seen file size.

By the way, you describe version 2) as "Dynamically exceed it...". For me, version 1) also dynamically extends the file. The only difference is that 1) extends only on-demand, whereas 2) extends eagerly.

Unless there are some additional constraints that we do not know I would recommend to keep it simple and stick with version 1).

Related Topic