gpt4 book ai didi

scala - scala 中的“死锁”

转载 作者:行者123 更新时间:2023-12-03 04:49:40 27 4
gpt4 key购买 nike

我想用 scala 重写 Sun 教程中有关 java 并发性的示例。原始代码在这里:http://java.sun.com/docs/books/tutorial/essential/concurrency/deadlock.html

此代码不正确。它卡住在注释指示的地方。有人能纠正这个吗?提前致谢。

import scala.actors.Actor

class Person(val name: String) extends Actor {

def bow(other: Person) {
other ! Bow(this)
}

private def bowBack(backTo: Person) {
println(this.name + " is bowing back to " + backTo.name)
backTo ! Bowed(this)
}

def act() {
while (true) {
receive {
case Bow(p) =>
println(this.name + " is bowing to " + p.name)
p ! BowBack(this)
println(" wating for bowing back...")
var received = false
while (true && received == false) {
receive { //blocked here
case Bowed(other) if p == other =>
println(" ... " + this.name + " has bowed to " + other.name)
received == true
}
}
println(this.name + " has bowed to " + p.name)
case BowBack(p) =>
println(this.name + " is bowing back to " + p.name)
p ! Bowed(this)
case "EXIT" => return
case x => println(x)
}
}
}
}

abstract case class Action()
case class Bow(person: Person) extends Action
case class BowBack(person: Person) extends Action
case class Bowed(person: Person) extends Action

object BowTest extends Application {
val a = new Person("Alphone")
val g = new Person("Gaston")
a.start()
g.start()

a ! Bow(g)
//g.bow(a)

a ! "EXIT"
g ! "EXIT"
}

最佳答案

第一个错误是你写了result == true。应将其更改为 result = true

您应该从 while 条件中删除 true 值。没有影响。

BowTest 对象中,您应该在 g.bow(a) 指令 Thread.sleep(1000) 之后添加,以便为 Actor 提供足够的时间是时候回复消息了。

这样你的代码就应该可以工作了。但仍然陷入僵局。如果您更改 a.bow(g) 中的 g.bow(a),执行将会卡住。这是由 receive block 引起的。每个参与者都在等待 Bowed 消息,但他们无法响应 BowBack 消息。

当您响应消息时,仅当您确定参与者将收到指定的消息时,才应使用 receive block 。但通常这在设计 Actor 时并不是一个好的做法。他们不应该阻止。 Actor 的主要目的是尽快响应消息。如果您必须执行一项大任务,您应该使用 futures,但在这种情况下不是必需的。

解决方案是将鞠躬的人保留在列表中。当 Actor 必须向某人鞠躬时,会将其添加到列表中。当 Actor 被列表中的某个人鞠躬时,就会将该人从列表中删除。


while (true) {
react {
case Bow(p) =>
println(this.name + " is bowing to " + p.name)
addPersonToBowList(p)
p ! BowBack(this)

case Bowed(other) if isPersonInBowList(other) =>
println(" ... " + this.name + " has bowed to " + other.name)
removePersonFromBowList(other)
case BowBack(p) =>
println(this.name + " is bowing back to " + p.name)
p ! Bowed(this)
case "EXIT" => exit()
case x => println(x)
}
}

关于scala - scala 中的“死锁”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2378218/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com