问题描述
我想知道您是否可以使用内存映射文件,并确保两个线程不会写入同一区域(例如,通过插入固定大小的记录),从而减轻了在应用程序级别进行同步的需要,即在我的代码中不使用关键部分或互斥体.
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:
但是它适用于属于同一进程的线程吗?这可能是合理的(因为我的写作是不相交的),但是我对内存映射的底层实现(例如,操作系统做的记账)了解得还不够.
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.
示例用例,其中每个线程执行myFunction
:
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.
推荐答案
无论从多个进程还是一个进程中的多个线程访问MMF视图,都需要添加同步.首先,在 one 进程中使用MMF进行内存共享没有任何意义.线程已经共享了地址空间.
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.
这篇关于内存映射文件线程安全吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!