gpt4 book ai didi

scala - 如何存储 scala actor 引用?

转载 作者:行者123 更新时间:2023-12-02 14:50:32 26 4
gpt4 key购买 nike

您好,我是 Scala 新手,我无法弄清楚如何在第二个 Actor 中存储 Actor 引用,以便稍后发送消息。在我的代码中,我尝试向一个 Actor 发送一条测试消息。当它收到此消息时,它应该存储对第二个参与者的引用(OutputChannel),并且稍后应该能够向第二个参与者发送消息。我不想使用reply(),因为我需要仅在调用响应时发送消息。这是代码。感谢您的帮助!

import scala.actors.Actor
import scala.actors.Actor._
import scala.collection.mutable.ArrayBuffer
import scala.actors.OutputChannel

object testactors {

case object TestMessage
case object Respond

class TestActor(name: String) extends Actor {
private var source : ArrayBuffer[OutputChannel[Any]] = new ArrayBuffer

def act() {
loop {
react{
case TestMessage =>
println("i received a TestMessage " + name)
source += sender
case Respond =>
println("i received a ResponseMessage " + name)
}
}
}

def sendMessage(dest: Actor) = dest ! TestMessage

def respond = {
println("responding... " + name)
source(0) ! Respond
}
}


def main(args: Array[String]) {
val actor1 = new TestActor("one")
actor1.start

val actor2 = new TestActor("two")
actor2.start

actor1.sendMessage(actor2)

Thread.sleep(5000)

actor2.respond
}
}

最佳答案

1.您可以创建一个集中的参与者注册表。为了避免重新发明轮子,您可以使用现有的良好实现 - Akka's Actor Registry (或者至少从中获得灵感)。

2您可以避免使用通过 react 循环传递的 Actor 引用的可变列表:

case class AddActor(actor: Actor)
case object NotifyAll

class StatefulActor extends Actor {

override def act = loop(Nil)

def loop(actors: List[Actor]):Unit = {
react {
case AddActor(actor) => println("Added new actor")
loop(actor :: actors)
case NotifyAll => println("Notifying actors: " + actors)
actors.foreach(_ ! "Hi!")
loop(actors)
case unknown => println("Unknown message: " + unknown)
loop(actors)
}
}

}

关于scala - 如何存储 scala actor 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4956579/

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