C 中的多缓冲区管理
您建议我做什么来缓冲 C 中的多个流(每个流需要它自己的缓冲区)?
我有点在脑海中组合了一个解决方案:
这是理论上的“伪代码”
[ptr, ptr, ptr, ptr ... ]
每个ptr
都是一个指向结构的指针:
{
stream_id
buff_ptr
}
stream_id
是流的 ID(我有该信息),而 buff_ptr
是指向某些 malloc
数据的指针。此外,缓冲区可能必须灵活,并且必须多次调用 malloc
和 free
才能使其灵活(至少我认为) em>
我基本上会通过遍历 ptr 数组来找到我需要的缓冲区
那么,这种“架构”好吗,或者是否有更好的架构
?为什么她需要那个?!”我已经在 Ruby/EventMachine 中创建了一个服务器,该协议真的很糟糕(至少可以说),我不知道如何处理它......除非有一种方法可以强制 EventMachine 为我缓冲它,那就是最好的解决方案,我想。
PS
:抱歉!
What would you recommend I do to buffer multiple streams (each stream would require it's own buffer) in C?
I sort of put together a solution in my head:
This is theoretical "pseudo code"
[ptr, ptr, ptr, ptr ... ]
Each ptr
is a pointer to a struct:
{
stream_id
buff_ptr
}
stream_id
is the ID of the stream (I have that information) and the buff_ptr
is a pointer to some malloc
ed data. Also, the buffers would probably have to be flexible and it'd have to call malloc
and free
a lot to make it flexible (at least I think it would?
I would basically find the buffer I need by iterating through the array of ptr
s.
So, is that "architecture" good, or is there a better one?
If anyone is wondering "Why the nyan does she need that?!" I've made a server in Ruby/EventMachine, the protocol is really rotten (to say the least) and I don't know how else to handle it... Unless there's a way to force EventMachine to buffer it for me, that would be the best solution, I suppose.
Thanks.
P.S: Sorry for the rave! ~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,这似乎是唯一的选择,但您可以更改一些内容:
malloc
和free
。使用realloc
代替迭代列表可能没问题,但如果有很多缓冲区
stream_id
进行搜索吗?例如glib2
提供了这样的哈希许多 API(例如 epoll)允许您将指针与 id(对于 epoll 来说是描述符)关联起来。当该 id 发生一些有趣的事情时,API 会将您的指针传递给您 ->零搜索会消耗 4-8 字节的内存。
Well, it seems the only option but you can change a few things:
malloc
andfree
. Userealloc
insteadIterating through the list could be OK but if there are a lot of buffers
stream_id
? For exampleglib2
provides such a hashMany APIs (for example epoll) allow you to associate a pointer with an id (a descriptor in the case of epoll). When something interesting happens to that id, the API passes you your pointer -> zero search at the expense of 4-8 bytes of memory.
使用 libev 制作一个简单的事件循环并让它处理轮询文件描述符。那里有很多示例,它的手册页 (
man 3 libev
) 是我读过的最好的手册页之一。只需定义一些回调并为您的读写池创建一些缓冲区即可。只要您在缓冲区填满或耗尽时分别阻止或跳过读取和写入,这些池的大小就可以保持静态。
Use libev to make a simple event loop and let it handle polling file descriptors. There are lots of examples out there and it's manual page (
man 3 libev
) is one of the best I've read.Just define a few callbacks and create some buffers for your read and write pools. The size of those pools can remain static so long as you block or skip your reads and writes when the buffer fills up or exhausts, respectively.