c++ - MapViewOfFile 和 VirtualLock

标签 c++ visual-studio winapi windows-7 file-mapping

以下代码是否会将数据从文件加载到系统内存中,以便对结果指针的访问永远不会阻塞线程?

auto ptr = VirtualLock(MapViewOfFile(file_map, FILE_MAP_READ, high, low, size), size); // Map file to memory and wait for DMA transfer to finish.
int val0 = reinterpret_cast<int*>(ptr)[0]; // Will not block thread?
int val1 = reinterpret_cast<int*>(ptr)[size-4]; // Will not block thread?

VirtualUnlock(ptr);
UnmapViewOfFile(ptr);

编辑:

在达蒙斯回答后更新。

auto ptr = MapViewOfFile(file_map, FILE_MAP_READ, high, low, size);

#pragma optimize("", off)
char dummy;
for(int n = 0; n < size; n += 4096)
    dummy = reinterpret_cast<char*>(ptr)[n];
#pragma optimize("", on)

int val0 = reinterpret_cast<int*>(ptr)[0]; // Will not block thread?
int val1 = reinterpret_cast<int*>(ptr)[size-4]; // Will not block thread?

UnmapViewOfFile(ptr);

最佳答案

如果文件的大小小于可笑的最大工作集大小(或者,如果您相应地修改了工作集大小),那么理论上是的。如果超过最大工作集大小,VirtualLock 将不执行任何操作(即失败)。

(在实践中,我发现 VirtualLock 相当......自由......在解释它应该做什么而不是它实际做什么时,至少在 Windows XP 下是这样 -在更现代的版本下可能会有所不同)

我过去一直在尝试类似的事情,现在我只是用一个简单的 for 循环(读取一个字节)来触摸 RAM 中我想要的所有页面。这不会留下任何问题并且有效,唯一可能的异常(exception)是页面在理论上可能会在触摸后再次被交换。实际上,这种情况永远不会发生(除非机器的 RAM 真的很低,然后就可以发生)。

关于c++ - MapViewOfFile 和 VirtualLock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968898/

相关文章:

c++ - Linux Ubuntu下绕行功能

c++ - 实现数据输入速记?

c++ - 如果重命名包含文件夹,EXE 将停止工作。 MSVCP90.dll

visual-studio - Visual Studio 2022 CMake 预设

c# - Gridview 中的 TextBox 返回 null 或 'System.Web.UI.WebControls.TextBox'

c++ - 在 C++ 中删除编译源的任何脚本

c++ - 最小网关: "No rule to make target"

winapi - TextOutW 在屏幕上与打印机上的显示不同

c# - 帮助 CredEnumerate

c++ - NtEnumerateKey() 的 KeyInformation 参数