gpt4 book ai didi

winapi - MapViewOfFile 内存映射是否被重用?

转载 作者:行者123 更新时间:2023-12-02 21:29:31 25 4
gpt4 key购买 nike

如果我在同一进程中为同一文件创建 2 个单独的映射,指针是否会共享?

换句话说:

LPCTSTR filename = //...

HANDLE file1 = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0);
HANDLE fileMapping1 = CreateFileMapping(file1, NULL, PAGE_READONLY, 0, 0, 0);
void* pointer1 = MapViewOfFile(fileMapping1, FILE_MAP_READ, 0, 0, 0);

CloseHandle(fileMapping1);
CloseHandle(file1);

HANDLE file2 = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0);
HANDLE fileMapping2 = CreateFileMapping(file2, NULL, PAGE_READONLY, 0, 0, 0);
void* pointer2 = MapViewOfFile(fileMapping2, FILE_MAP_READ, 0, 0, 0);

CloseHandle(fileMapping2);
CloseHandle(file2);

pointer1会等于pointer2吗?

我问的原因是我有几个线程需要在一个大(300+MB)文件中搜索,并且我想为此使用内存映射。然而,该进程需要能够在旧的 32 位 xp 机器上运行,因此如果每个线程在虚拟内存中分配自己的副本,那么我可能会耗尽内存。

最佳答案

msdn has documented it字里行间:

As mentioned above, you can have multiple views of the same memory-mapped file, and they can overlap. But what about mapping two identical views of the same memory-mapped file? After learning how to unmap a view of a file, you could come to the conclusion that it would not be possible to have two identical views in a single process because their base address would be the same, and you wouldn't be able to distinguish between them. This is not true. Remember that the base address returned by either the MapViewOfFile or the MapViewOfFileEx function is not the base address of the file view. Rather, it is the base address in your process where the view begins. So mapping two identical views of the same memory-mapped file will produce two views having different base addresses, but nonetheless identical views of the same portion of the memory-mapped file.

另外:

The point of this little exercise is to emphasize that every view of a single memory-mapped file object is always mapped to a unique range of addresses in the process. The base address will be different for each view. For that reason the base address of a mapped view is all that is required to unmap the view.

关于winapi - MapViewOfFile 内存映射是否被重用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22659282/

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