【发布时间】:2021-11-04 13:27:10
【问题描述】:
在跨平台(Linux 和 Windows)实时应用程序中,我需要在 C++ 进程和我都管理的 Python 应用程序之间共享数据的最快方式。我目前使用套接字,但在使用高带宽数据(30 fps 的 4K 图像)时速度太慢。
我最终想使用multiprocessing shared memory,但我的第一次尝试表明它不起作用。我使用 Boost.Interprocess 在 C++ 中创建共享内存,并尝试像这样在 python 中读取它:
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
int main(int argc, char* argv[])
{
using namespace boost::interprocess;
//Remove shared memory on construction and destruction
struct shm_remove
{
shm_remove() { shared_memory_object::remove("myshm"); }
~shm_remove() { shared_memory_object::remove("myshm"); }
} remover;
//Create a shared memory object.
shared_memory_object shm(create_only, "myshm", read_write);
//Set size
shm.truncate(1000);
//Map the whole shared memory in this process
mapped_region region(shm, read_write);
//Write all the memory to 1
std::memset(region.get_address(), 1, region.get_size());
std::system("pause");
}
还有我的python代码:
from multiprocessing import shared_memory
if __name__ == "__main__":
shm_a = shared_memory.SharedMemory(name="myshm", create=False)
buffer = shm_a.buf
print(buffer[0])
我收到系统错误FileNotFoundError: [WinError 2] : File not found。所以我猜它只能在 Python 多处理内部工作,对吧? Python 似乎找不到在 C++ 端创建的共享内存。
另一种可能性是使用mmap,但恐怕它不如“纯”共享内存(不使用文件系统)快。如Boost.interprocess documentation所述:
但是,由于操作系统必须将文件内容与内存内容同步,内存映射文件不如共享内存快
我不知道它慢到什么程度。我只是更喜欢最快的解决方案,因为这是我目前应用程序的瓶颈。
【问题讨论】:
-
什么是“纯”共享内存?
-
不使用会增加开销的文件系统。我会努力改进我的帖子。
-
您似乎将“我的共享内存的名称在文件系统中”与“我的共享内存的内容在磁盘上”混淆了。他们是分开的。继续,将 shm 文件放在其他程序可以找到的目录中。
-
这是在 Windows 上吗?您可能应该使用平台标记您的问题,因为共享内存性能很可能具有特定于平台的详细信息。
-
你打算在 Python 中用这些数据做什么?你说的是每秒一千兆字节。除非您立即将其改组为更多基于 C 的代码(如 numpy),否则您将无法跟上。
标签: c++ python-3.x shared-memory boost-interprocess