加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

windows – 内存映射文件是否安全

发布时间:2020-12-14 04:31:05 所属栏目:Windows 来源:网络整理
导读:我想知道你是否可以使用 memory-mapped files对单个文件进行多线程写入,并确保两个线程不写入同一区域(例如,通过交错固定大小的记录),从而减少了在应用程序中同步的需要级别,即我的代码中没有使用关键部分或互斥锁. 然而,谷歌搜索了一下后,我仍然不确定.微软
我想知道你是否可以使用 memory-mapped files对单个文件进行多线程写入,并确保两个线程不写入同一区域(例如,通过交错固定大小的记录),从而减少了在应用程序中同步的需要级别,即我的代码中没有使用关键部分或互斥锁.

然而,谷歌搜索了一下后,我仍然不确定.微软的这个link说:

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.

但它是否适用于属于同一进程的线程?这似乎是合情合理的(因为我的写作是不相交的),但我不太了解内存映射的底层实现(例如操作系统的簿记).

示例用例,其中myFunction由每个线程执行:

// 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;
}

如果我要运行它,等待线程完成,取消映射文件并退出,我最终会得到一个包含连续整数的文件吗?

我很感激能够得到明智的答复.

解决方法

无论是从一个进程内的多个进程还是多个线程访问MMF视图,都需要添加同步. Fwiw,在一个进程中使用MMF进行内存共享没有任何意义.线程已经共享地址空间.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读