Windows 7 上最快的 IPC 方法

2021-12-24 00:00:00 windows ipc c c++ boost

Windows 7 上最快的进程间通信 (IPC) 方法是什么?我们只想共享一个内存块(双向).

What is the fastest possible Interprocess Communication (IPC) method on Windows 7? We would like to share only a memory blocks (two-way).

ReadProcessMemory 还是别的什么?我们想使用普通的 C 但是,例如,Boost 库对 IPC 使用什么?

Is it ReadProcessMemory or something else? We would like to use plain C but, for example, what does Boost library use for IPC?

推荐答案

ReadProcessMemory 甚至不应该被列为 IPC 方法;是的,它可以这样使用,但它主要用于调试目的(如果你检查它的参考,它在调试函数"类别下),而且它肯定比真实"共享内存慢,因为它复制 一个进程的内存到指定的缓冲区,而真正的共享内存没有这个开销.

ReadProcessMemory shouldn't even be listed as an IPC method; yes, it can be used as such, but it exists mainly for debugging purposes (if you check its reference, it's under the category "Debugging functions"), and it's surely slower than "real" shared memory because it copies the memory of a process into the specified buffer, while real shared memory doesn't have this overhead.

Windows 支持的 IPC 方法的完整列表可用 在 MSDN 上;尽管如此,如果您只有两个应用程序想要共享一个内存块,您应该使用 CreateFileMapping/MapViewOfFile 创建一个命名的内存映射文件(由分页文件支持),那应该是最直接、最快的方法了.文件映射的详细信息在其页面 在 MSDN 上.

The full list of IPC methods supported by Windows is available on the MSDN; still, if you just have two applications that want to share a memory block, you should create a named memory-mapped file (backed by the paging file) with CreateFileMapping/MapViewOfFile, that should be the most straightforward and fastest method. The details of file mapping are described on its page on MSDN.

相关的 Boost IPC类 可以充当共享内存的瘦包装器,AFAIK 它只封装对相关系统特定 API 的调用,但最终您会获得指向共享内存块的常用指针,因此操作应该一样快就像使用原生 API 一样.

The relevant Boost IPC classes can act as a thin wrapper around shared memory, AFAIK it only encapsulates the calls to the relevant system-specific APIs, but in the end you get the usual pointer to the shared memory block, so operation should be as fast as using the native APIs.

因此我建议您使用 Boost.Interprocess,因为它是可移植的,对 C++ 友好(它提供 RAII 语义)并且在创建共享内存块后不会给您带来任何性能损失(它可以在共享内存上提供附加功能,但它们都是可选的――如果你只想要共享内存,你就可以了).

Because of this I advise you to use Boost.Interprocess, since it's portable, C++-friendly (it provides RAII semantics) and does not give you any performance penalty after the shared memory block has been created (it can provide additional functionalities on shared memory, but they are all opt-in - if you just want shared memory you get just it).

相关文章