内存映射文件线程安全吗 [英] Are memory-mapped files thread safe

查看:133
本文介绍了内存映射文件线程安全吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道您是否可以使用内存映射文件,并确保两个线程不会写入同一区域(例如,通过插入固定大小的记录),从而减轻了在应用程序级别进行同步的需要,即在我的代码中不使用关键部分或互斥体.

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:

首先,因为两个过程都明显节省了资源 共享内存的物理页面和硬盘的页面 用于备份内存映射文件的存储.第二,只有一个 一组数据,因此所有视图始终保持一致.这 表示通过一个对内存映射文件中的页面进行的更改 流程的视图会自动反映在 在另一个进程中的内存映射文件.本质上,Windows NT不是 需要进行任何特殊簿记以确保数据的完整性 到两个应用程序.

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.

示例用例,其中每个线程执行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.

这篇关于内存映射文件线程安全吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆