Handmade Network»Forums
60 posts
None
Keep two regions of memory in sync
Edited by erpeo93 on
Hi,

I'm searching for the simplest and easiest way to keep two memory regions of the same size aligned.
I was hoping that the operating systems would offer an api for this, something like:

SyncMemory sync = StartSyncMemory(prt1, ptr2, size);
StopSyncMemory(sync);

But it doesn't seems to be the case.

The only suggested solution I could find on the web is to mark the first region as readonly and have a write to the other region on the callback, but it seems quite slow to me, and of course I would have to deal with multithread to some extent I guess...
Do you happen to know if there's something that can do this at a os level? Something like mmap but for memory instead of files...

Another "could-do-it" solution would be vanilla mmap (yes I want to save the entire state of the game, you guessed it), but I'm talking about GB's of memory, and a lot of writes, don't know what the performances of mmap are with these sizes... Do you have any resources on that?


Thank you very much,
Leonardo
Mārtiņš Možeiko
2562 posts / 2 projects
Keep two regions of memory in sync
Edited by Mārtiņš Možeiko on
I haven't tried it, but it think you can do this with shared memory.
First open shared memory with shm_open, set its size with ftruncate. Then do mmap on shared memory file handle with MAP_SHARED flag to get pointer to memory. And then do second call with mmap on the same shared memory file handle with MAP_PRIVATE flag. These should be two different pointers, but second pointer will point to memory that will always see data what is changed in memory pointer by first pointer.
Not sure how portable this is across OS'es.
60 posts
None
Keep two regions of memory in sync
Thank you for the reply Martin, I'll defitively give it a shot.

Surfing the web I've also find this nice api on windows: https://docs.microsoft.com/en-us/...oryapi/nf-memoryapi-getwritewatch

It would seems that it allows me to query the dirty pages from a memory region, and at that point is easy for me to copy all the modified pages to the "mirror" region, pretty simple.
Unfortunately linux hasn't anything like this, but I was thinking that I could keep my "own" dirty bits and set them on SIGSEGV signals...

It should work and should be simple enough to implement, but definitively I'll also try your "direct" solution :)

Thank you very much.
Leonardo