C:对于这个需求,有什么比 FIFO 队列实现更好的方法吗?
在我的一个程序中,有多个客户端,每个客户端都有自己的缓冲区。在无限循环中,我检查是否有任何客户端有任何数据要写入磁盘。如果是这样,那么我也会这样做并继续。
现在,因为客户端写入的数据实际上不在我的控制范围内(某些计算的结果),所以我需要一个动态缓冲区。因此伪代码如下所示:
//If data is ready
//Append(client_id, line)
void Append(int client_id, char *line) {
if(client_id.buffer == NULL) {
buffer = (char*)malloc(BUFFERSIZE * sizeof(char));
//Copy line into buffer
} else {
//Realloc the buffer if insufficient space and append this
//line to the existing buffer
}
}
或者另一种方法是使用简单的消息队列。我会继续将任何消息(字符串)添加到现有队列中,然后读取它们。还有其他更好的方法吗?
In one of my programs, there are multiple clients and each client has its own buffer. In an infinite loop, I check if any of the client has any data to be written to disk. If it does, then I do the same and continue.
Now, because the client writes data that is not really in my control (result of some computations), I need a dynamic buffer. So the pseudo code would look like this:
//If data is ready
//Append(client_id, line)
void Append(int client_id, char *line) {
if(client_id.buffer == NULL) {
buffer = (char*)malloc(BUFFERSIZE * sizeof(char));
//Copy line into buffer
} else {
//Realloc the buffer if insufficient space and append this
//line to the existing buffer
}
}
or the other approach would be to use a simple message queue. I would keep adding whatever messages (strings) to an existing queue and then read them off. Is there some other better approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可能没有完全理解你的架构,但我的理解是客户端通过传递它的 ID 和 char * 来调用你,并希望你将其写入磁盘。
您是否有理由必须复制原始缓冲区?通过这样做,你的所有内容都会在内存中保存两次,并且有机会搞乱内存管理。如果可能的话,只需处理原始缓冲区即可。
这里是否发生了一些线程?如果这都是单线程的(从这个“服务器”代码的角度来看,至少......一个线程来轮询和写入结果),那么您实际上并不需要 FIFO,因为事情只会按照您轮询的顺序发生客户。如果有一个(或多个)线程来轮询客户端,并有一个单独的线程来写入结果,则 FIFO 是组织线程通信的好方法。
I might not have fully understood your architecture, but my understanding is that a client calls you by passing it's ID and a char * and wants you to write it to disk.
Is there a reason you have to copy the original buffer? By doing that, you have everything in memory twice and an opportunity to mess up memory management. If possible, just work off of the original buffer.
Is there some threading happening here? If this is all single threaded (from the point of view of this "server" code at least... one thread to poll and write results), you don't really need a FIFO since things will just happen in the order you poll clients. If there is a thread (or multiple ones) to poll clients and a separate thread to write the results, a FIFO is a great way to organize thread communication.