scala邮箱大小限制
我可以在 Scala 中设置演员邮箱的最大大小吗?
以生产者-消费者问题为例。使用线程,当缓冲区填满时,我可以阻止生产者。我看到了几个用 Scala 编写的生产者-消费者示例,它们都使用 Actor,并将邮箱用作“缓冲区”。我可以设置邮箱大小以使生产者等待消费者准备好吗?还有其他优雅的解决方案可以避免邮箱不受控制的增长吗?
Can I set maximum size for an actor's mailbox in Scala?
Take the Producer-Consumer problem. With threads I can block the producers when the buffer fills up. I saw a couple of producer-consumer examples written in Scala and they all use actors with mailboxes used as a "buffer". Can I set mailbox size to cause producers to wait until a consumer is ready? Any other elegant solution to avoid uncontrollable growth of mailboxes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建一个角色来充当生产者和消费者之间的缓冲区。缓冲区将其邮箱检查到其循环数据。当缓冲的产品数量过多时,它会向生产者发送“过载”消息;并在一切恢复正常后发送“明确”消息。如果消息太多,它只会删除传入的消息(或最旧的消息)。
消费者主动从缓冲区请求产品,缓冲区又发回一种产品。如果缓冲区为空,消费者将继续等待输入。
生产者将产品发送到缓冲区参与者。如果它收到“过载”消息,它可以停止生产,或者可以继续生产,因为它知道产品可能会被丢弃。
当然,这个逻辑可以直接实现到生产者或消费者本身,但是单独的缓冲区将允许您更轻松地引入多个生产者和/或消费者。
You can create an actor that acts as a buffer between the producer and consumer. The buffer checks out its mailbox to its loop data. It sends back an "overload" message to the producer when the number of buffered products is too high; and sends a "clear" message once everything is back in order. In case of too many messages it simply drops incoming ones (or oldest ones).
The consumer actively requests for products from the buffer, which in turn sends back one product. If the buffer is empty, the consumer keeps waiting for the input.
The producer sends products to the buffer actor. If it receives an "overload" message it can stop production, or it can continue producing, knowing the fact that the products might get dropped.
Of course this logic could directly be implemented into the producer or consumer itself, but a separate buffer will allow you to introduce multiple producers and/or consumers more easily.
Actor.mailboxSize
方法返回 Actor 邮箱中待处理消息的数量。这可以用于以各种方式限制生产者。
例如,一种可能性可能是,
生产者检查消费者的
mailboxSize
是否大于某个阈值。如果是,那么它会向消费者发送一个SpecialMessage
,并阻塞信号量。当消费者收到此SpecialMessage
时,它会释放信号量。生产商现在可以愉快地继续其业务了。这可以避免轮询以及任何丢失的消息。
The
Actor.mailboxSize
method returns the number of pending messages in the Actor's mailbox.This can be used for throttling the producer in various ways.
For example, one possibility could be,
The producer checks if the consumer's
mailboxSize
is greater than some threshold. If it is, then it sends aSpecialMessage
to the consumer, and blocks on a semaphore. When the consumer receives thisSpecialMessage
it releases the semaphore. The producer can now merrily continue it's business.This avoids polling as well as any dropped messages.