简体   繁体   English

内存池和缓冲区C ++

[英]Memory pools and buffers C++

I have a few questions about buffers and memory pools i would like to have answered. 我想回答一些关于缓冲区和内存池的问题。

Say i have a server, sending and receiving ~50-100+ msg / second. 假设我有一台服务器,每秒发送和接收〜50-100 + msg。 All msgs come in various sizes. 所有味精都有各种尺寸。 How would you go about it to make the best of the memory management here ? 您将如何利用它来充分利用此处的内存管理? My original plan was using fixed sized buffer nodes, and pool them, something like: 我最初的计划是使用固定大小的缓冲节点,并对其进行缓冲,例如:

struct buffer{
    uint8_t  data[512];
    uint32_t end;
    buffer*  next;
}
buffer* b = pool_get_new_buffer();

So when a msg is sent, i create one or more buffers depending on the size and link them together. 因此,当发送味精时,我会根据大小创建一个或多个缓冲区并将它们链接在一起。 This way i dont have be afraid of fragmentation in the pool it self. 这样,我就不必担心池中的碎片本身。 (or thats atleast what i think). (或者多数民众赞成在我的想法)。 But on small msg, its a waste of space. 但是在小的味精上,这是浪费空间。

But reading more and more and checking out code on the internet, it looks like nobody uses this approach at all. 但是,越来越多的人阅读并在Internet上签出代码,似乎根本没有人使用这种方法。 So what would be a better approach ? 那么,哪种方法更好呢? Allocating memory from the pool depending on msg size ? 根据msg大小从池中分配内存?

EDIT : So what im after here is maybe a more indept comparison of the different approaches. 编辑 :所以我在这里之后可能是对不同方法的更深入的比较。

If i use the chained buffer approach im guessing i will keep fragmentation at its lowest but on the other hand i would guess that doing memcpy for every buffer in the chain comes at a cost as well. 如果我使用链式缓冲区方法,我想我会将碎片保持在最低水平,但另一方面,我猜想对链中的每个缓冲区执行memcpy也会带来成本。 But then again, allocating a large enough buffer and doing a single memcpy must have its downsides as well, even though most people choose this approach anyway. 但是话又说回来,即使大多数人仍然选择这种方法,分配足够大的缓冲区并执行一次memcpy也必须有其缺点。

How about having a single buffer, say 0.5/1MB in size. 单个缓冲区大小为0.5 / 1MB怎么样。 This obviously depends on the target OS/device and possibly your maximum message size. 显然,这取决于目标操作系统/设备以及最大消息大小。 Also, have your server include the packet size. 另外,让您的服务器包含数据包大小。 Assuming your packet doesn't exceed the single buffer size you can download data into the buffer, process it and then mark the memory as available. 假设您的数据包不超过单个缓冲区的大小,则可以将数据下载到缓冲区中,进行处理,然后将内存标记为可用。 I've used this approach for single client-server applications. 我已将这种方法用于单个客户端服务器应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM