作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用Scala 2.8 RC1或更高版本,什么是最好的(最简单和/或最直接的)方法(从同一 Actor 的act()方法内部)“窥视” Actor 邮箱中的等待消息?队列,而不必以任何方式响应/接收消息和/或打乱邮箱的当前内容。
这样做的目的是使参与者可以通过首先确定其余邮箱消息是否是必须处理的消息来确定是否安全处理退出请求,而不是通过立即停止参与者来丢弃它。
最佳答案
您不需要偷看。只需跟踪已请求退出的事实,并使用reactWithin(0)确定在请求退出后队列何时为空。
import scala.actors._
sealed case class Message
case object Exit extends Message
case class Unimportant(n:Int) extends Message
case class Important(n:Int) extends Message
class SafeExitingActor extends Actor {
def act : Nothing = react {
case Exit => {
println("exit requested, clearing the queue")
exitRequested
}
case message => {
processMessage(message, false)
act
}
}
// reactWithin(0) gives a TIMEOUT as soon as the mailbox is empty
def exitRequested : Nothing = reactWithin(0) {
case Exit => {
println("extra exit requested, ignoring")
exitRequested // already know about the exit, keep processing
}
case TIMEOUT => {
println("timeout, queue is empty, shutting down")
exit // TIMEOUT so nothing more to process, we can shut down
}
case message => {
processMessage(message, true)
exitRequested
}
}
// process is a separate method to avoid duplicating in act and exitRequested
def processMessage(message : Any, importantOnly : Boolean) = {
message match {
case Unimportant(n) if !importantOnly => println("Unimportant " + n)
case Unimportant(n) => () // do nothing
case Important(n) => println("Important! " + n)
}
Thread sleep 100 // sleep a little to ensure mailbox backlog
}
}
object TestProcessing {
def main(args : Array[String]) {
val actor = new SafeExitingActor()
actor.start()
for (i <- 1 to 10) {
actor ! Unimportant(i)
actor ! Important(i)
}
actor ! Exit
for (i <- 11 to 20) {
actor ! Unimportant(i)
actor ! Important(i)
}
actor ! Exit
actor ! Important(100)
}
}
Unimportant 1
Important! 1
Unimportant 2
Important! 2
Unimportant 3
Important! 3
Unimportant 4
Important! 4
Unimportant 5
Important! 5
Unimportant 6
Important! 6
Unimportant 7
Important! 7
Unimportant 8
Important! 8
Unimportant 9
Important! 9
Unimportant 10
Important! 10
exit requested, clearing the queue
Important! 11
Important! 12
Important! 13
Important! 14
Important! 15
Important! 16
Important! 17
Important! 18
Important! 19
Important! 20
extra exit requested, ignoring
Important! 100
timeout, queue is empty, shutting down
关于scala - 窥视Scala Actor 邮箱的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2721337/
在升级到 Oracle 11g 后,我在优化 Oracle 查询时遇到了问题,这个问题开始让我有点抓狂。 注意,这个问题现在已经被完全编辑过了,因为在创建一个简单的测试用例后我有更多的信息。原始问题可
我正在尝试在支持 iOS 9 的应用程序中执行 Peek 和 Pop。有问题的 View 有一个 UITableView,所以我的代码中有: - (UIViewController *)preview
我不知道如何在 Python 生成器中向前看一个元素。我一看就不见了。 这就是我的意思: gen = iter([1,2,3]) next_value = gen.next() # okay, I
我是一名优秀的程序员,十分优秀!