boost::managed_shared_memory 正在使用我硬盘上的文件吗?

Is boost::managed_shared_memory using a file on my hard drive?

当我创建一个新的 boost::interprocess::managed_shared_memory 时,我可以看到 C:\ProgramData\boost_interprocess71641094\NAME_OF_SHARED_MEMORY 中出现了一个文件,其大小似乎与创建的共享内存的大小相匹配。

我对 documention 的理解是,有两个广泛使用的对象可用于在进程之间共享内存(在 managed_shared_memory 的范围内):

managed_shared_memory 使用 basic_managed_shared_memory 实现。我假设这个实现是正确的 shared memory 而不是 memory mapped file.

看到它使用一个文件,我很困惑。这些托管共享内存是否都基于内存映射文件实现?

是 Windows 上唯一避免内存映射文件 windows_shared_memory 的增强共享内存解决方案吗?

注意:我在 Windows 10,在 VS2013 上使用 VC++。

使用 managed_shared_memory 时可以重现在 ProgramData 中创建文件行为的代码示例:

#include <boost/interprocess/managed_shared_memory.hpp>

int main(int argc, char *argv[])
{
  boost::interprocess::permissions permissions;
  permissions.set_unrestricted();

  boost::interprocess::managed_shared_memory* sharedMemory;
  sharedMemory = new boost::interprocess::managed_shared_memory(
  {
    boost::interprocess::open_or_create,
    "NAME_OF_SHARED_MEMORY",
    400000,
    0,
    permissions
  }
  );

  return 0;
}

您的假设是正确的。 Boost 文档中的“Emulation for systems without shared memory objects”部分解释了正在发生的事情:

Boost.Interprocess provides portable shared memory in terms of POSIX semantics. Some operating systems don't support shared memory as defined by POSIX:

  • Windows operating systems provide shared memory using memory backed by the paging file but the lifetime semantics are different from the ones defined by POSIX (see Native windows shared memory section for more information).

...

In those platforms, shared memory is emulated with mapped files created in a "boost_interprocess" folder created in a temporary files directory. In Windows platforms, if "Common AppData" key is present in the registry, "boost_interprocess" folder is created in that directory (in XP usually "C:\Documents and Settings\All Users\Application Data" and in Vista "C:\ProgramData"). For Windows platforms without that registry key and Unix systems, shared memory is created in the system temporary files directory ("/tmp" or similar).

Because of this emulation, shared memory has filesystem lifetime in some of those systems.

正如您已经指出的,作为替代方案,您可以使用 native windows shared memory objects (using windows_shared_memory). It will use a shared memory object backed by the pagefile instead of a file being created in C:\ProgramData. In general, this will not use the filesystem (see: )。如果可移植性不是问题,这可能是一种更好的方法,因为它允许与其他使用共享内存但不依赖 Boost.Interprocess.

的应用程序进行互操作。