Are memory-mapped files thread safe

╄→尐↘猪︶ㄣ 提交于 2019-12-22 07:05:04

问题


I was wondering whether you could do multithreaded writes to a single file by using memory-mapped files, and making sure that two threads don't write to the same area (e.g. by interleaving fixed-size records), thus alleviating the need for synchronization at the application level, i.e. without using critical sections or mutexes in my code.

However, after googling for a bit, I'm still not sure. This link from Microsoft says:

First, there is an obvious savings of resources because both processes share both the physical page of memory and the page of hard disk storage used to back the memory-mapped file. Second, there is only one set of data, so all views are always coherent with one another. This means that changes made to a page in the memory-mapped file via one process's view are automatically reflected in a common view of the memory-mapped file in another process. Essentially, Windows NT is not required to do any special bookkeeping to ensure the integrity of data to both applications.

But does it apply to threads belonging to the same process? It would be plausible (since my writes are disjoint), but I don't know enough about the underlying implementation of memory mapping (e.g. what book-keeping the OS does) to be sure.

Example use case, 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, unmap the file and exit, would I end up with a file containing consecutive integers?

I would be grateful for an informed answer.


回答1:


You'll need to add the synchronization regardless if the MMF view is accessed from multiple processes or multiple threads inside one process. Fwiw, it doesn't make any sense to use an MMF for memory sharing inside one process. Threads already share the address space.




回答2:


But does it apply 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 that change.

You need to ensure the threads coordinate their changes so no thread is accessing an inconsistent view (eg. all access is via a critical section).



来源:https://stackoverflow.com/questions/8035595/are-memory-mapped-files-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!