Are memory mapped files streams

I was wondering if you can make multi-threaded writes to one file using memory-mapped files and making sure that two streams do not work, t write to the same area (for example, by interleaving fixed-size records), thereby facilitating the need synchronization at the application level, that is, without the use of critical sections or mutexes in my code.

However, after you have worked a little, I'm still not sure. This link from Microsoft says:

Firstly, there is an obvious saving of resources, since both processes share both the physical memory page and the hard drive page storage used to back up the memory mapped file. Secondly, there is only one data set, so all views are always consistent with each other. This means that changes made to a page in a file with memory mapping through one type of process are automatically reflected in the general form of a file with memory mapping in another process. In fact, Windows NT is not required for special bookkeeping to ensure data integrity for both applications.

But is it applicable to threads belonging to the same process? That would be believable (since my records don't overlap), but I don’t know enough about the underlying implementation of memory matching (for example, what the OS account does).

Usage example where myFunction is executed by each thread:

 // crt - index of current thread, in 0..n-1 // n - thread count // memArea - pointer to memory location obtained from mapping a file void myFunction(int crt, int n, int*memArea){ for (int i=1; i<512; i++) memArea[ ( sizeof(int)*( n*i + crt ) ] = n*i+crt; } 

If I were to run this, wait for the threads to finish, unzip the file and exit it, do I get a file with integers?

I would be grateful for a reasonable answer.

+4
source share
2 answers

You will need to add synchronization regardless of whether the MMF view is available from multiple processes or multiple threads within the same process. Fwiw, it makes no sense to use MMF to exchange memory within one process. Themes already have an address space.

+4
source

But is it applicable to threads belonging to the same process?

Yes. If one thread changes part of the data in the mapping, then all other threads immediately see this change.

You need to make sure that the threads coordinate their changes, so the thread does not access an inconsistent representation (for example, all access is through a critical section).

+2
source

Source: https://habr.com/ru/post/1379976/


All Articles