简体   繁体   English

管道中多个固定大小记录的读取器

[英]multiple readers of fixed size records from a pipe

If you make a pipe, you can fork a bunch of children (workers, say) and have each read from the pipe. 如果您制作管道,则可以分叉一堆孩子(例如,工人),并从管道中读取每个孩子。 If the parent process writes data to the pipe, it's unspecified which worker'll get it, and if each worker reads like 1000 bytes at a time, and the parent writes like 225 and then 430, it's unspecified which worker will get how many bytes. 如果父进程将数据写入管道,则未指定将由哪个工作程序获取数据,并且如果每个工作程序一次读取的数据为1000个字节,而父进程则先写入的数据为225然后为430,则未指定哪个工作程序将获得多少字节。 。 But, I think with some underlying assumptions it might actually work to have multiple readers on a pipe? 但是,我认为基于一些基本假设,在管道上具有多个读取器实际上可能有效?

1) fixed size messages. 1)固定大小的消息。 workers only read messages on one fixed size. 工作人员只能阅读固定大小的邮件。 The server only writes messages of that size. 服务器仅写入该大小的消息。

2) the workers are used as a "pool" to do the job of 1 worker, but in parallel for blocking operations. 2)工人用作“池”来完成1名工人的工作,但并行执行阻塞操作。 So not every worker needs (or should) receive every message. 因此,并非每个工人都需要(或应该)接收每条消息。 They want to split the messages according to who's available to wait for them. 他们想根据谁有空等待他们来拆分消息。

I made a thing which makes a pipe per worker, and just randomly writes to one pipe or another, waving a rubber chicken in hopes that particular worker doesn't happen to be the one that's stuck in a long operation. 我做了一件让每个工人用一根管子的东西,然后随机地写到一个或另一个管子里,挥舞着橡皮鸡,希望那个特殊的工人不会碰到长时间工作的人。 But couldn't I have them all read from 1 pipe, and any worker that was free would block on reading it, thus get woken up on-demand by writes to that pipe? 但是我不能让它们全部从1个管道中读取,并且任何空闲的工作人员都将阻止读取它,从而因对该管道的写入而按需唤醒?

write() returns the number of bytes actually written. write()返回实际写入的字节数。 Imagine your pipe has a 1 MB buffer provided by the system, and you have written 10 bytes fewer than 1 MB. 假设您的管道具有系统提供的1 MB缓冲区,并且您写入的字节数少于1 MB。 Next time you try to write 1000 bytes, you will only write 10 bytes. 下次尝试写入1000个字节时,您将只写入10个字节。 Now what? 怎么办? The first reader who tries will get those 10 bytes, but has no way to make sure no one else "steals" the rest of the message. 尝试的第一个阅读器将获得这10个字节,但无法确保没有其他人“窃取”消息的其余部分。

You should instead consider a message-oriented API, such as SysV or POSIX Message Queues: System V IPC vs POSIX IPC 您应该考虑使用面向消息的API,例如SysV或POSIX消息队列: System V IPC vs POSIX IPC

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

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