在 C++ 中在内存中创建大流

Creating large stream in memory in c++

我正在使用创建大量 (>4GB) 二进制数据的外部库。我想缓冲这些数据并在它仍在创建时将其提供给第二个库。

我的程序是 64 位进程,运行 在 Linux 上。我无法就其 RAM 运行 系统做出任何保证。

对于第一个库,我实现了库调用的虚函数,以向我提供二进制数据:

virtual void put_data(uint8_t* data, size_t s_data);

我可以自由地使用这些数据在实现的功能中做任何我想做的事情。

第二个库同样需要 100 字节的数据块。该函数如下所示:

void write(const uint8_t* buffer);

所以理论上我可以做的是在一个线程中启动第一个库,在第二个线程中启动第二个库,当数据来自第一个库时,循环将此数据提供给第二个库,如果它可用。现在显然我不能只转发缓冲区,因为它们可能有不同的大小。在 C++ 中是否有一种方便的方法,或者我是否必须为此编写一个新的 Class?

如果您有权访问 boost,则可以使用他们的共享内存库。

boost interprocess

首先,您可以将文件写入 tmpfs mounted file system. Then, the files are sitting in virtual memory, and, as long as they fit in RAM, no disk IO happens. BTW Linux has a good page cache so when a process writes some file which is quickly read and consumed, few disk IO happens (even on ordinary file systems). Read also http://linuxatemyram.com/

既然你提到了运行两个线程,你可以设置一个pipe(7) to communicate between the threads (with one thread writing to the pipe, and another one reading from it). Read Advanced Linux Programming & some pthreads tutorial. Consider also learning C++11 programming, redesigning your program entirely and using the many features (like closures - learn also more about continuations and CPS,容器,智能指针,...)在C+中引入+11.

最后,您可以将所有数据保存在虚拟内存中,也许使用 std::stringstream, open_memstream(3),或者只是 std::string

另见 fifo(7), shm_overview(7), sem_overview(7). Learn more about C++11 threads and more generally about Inter Process Communication techniques & event loops (e.g. above poll(2) ...)。