gpt4 book ai didi

windows - 内存映射文件是线程安全的吗

转载 作者:可可西里 更新时间:2023-11-01 13:30:29 26 4
gpt4 key购买 nike

我想知道您是否可以使用 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 View ,您都需要添加同步。 Fwiw,在 one 进程内使用 MMF 进行内存共享没有任何意义。线程已经共享地址空间。

关于windows - 内存映射文件是线程安全的吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8035595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com