gpt4 book ai didi

scala - 在scala中将值从一个 Actor 传递给另一个 Actor

转载 作者:行者123 更新时间:2023-12-02 22:30:57 27 4
gpt4 key购买 nike

你们中的任何人都可以帮助我理解传入的基本消息吗scala 使用 Actor 模型?

我正在尝试编写一个包含 3 个 Actor 的简单程序。

  1. Actor “BossActor”创建了 2 个 Actor “Actor1”和“Actor2”

  2. “Actor1”接受 2 个整数参数 -> 找到它们的总和 -> 将总和传递给 Actor 2

  3. “Actor2”打印总和

package actorsSum

import scala.actors.Actor
import scala.actors.Actor._

case object BossActor
case object Actor1
case object Actor2

object SumOf2Numbers extends App
{

print ("Enter Num1 : ")
val Num1 = readInt()
print ("Enter Num2 : ")
val Num2 = readInt()

var Sum = 0

val bossActor = new BossActor(Num1,Num2,Sum)
bossActor.start

}

/** Boss Actor which creates and controls all subsequent actors */
class BossActor(Num1: Int, Num2: Int, Sum: Int) extends Actor {
def act() {

val act1 = new Actor1(Num1,Num2)
val act2 = new Actor2(Sum)
act1.start
act2.start

}
}

/** Actor to find sum of the numbers */

class Actor1 (Num1: Int, Num2: Int) extends Actor {
def act() {

val Grandtotal = Num1 + Num2

/** send "Grandtotal" to Actor2 */
// act2 ! Grandtotal

}
}

/** Actor to print the sum */

class Actor2(Sum: Int) extends Actor {
def act() {

react{

/** print the sum */

case Actor1 => println ("Sum: " + Sum)

case Sum => println ("Sum: " + Sum)


}
}
}

最佳答案

我会采取不同的方法。 Actor 接收消息并对其使用react。因此,您应该做的是构建一个 actor,它接收对 2 个数字求和的请求,并将它们发送到也在消息中指定的接收者。这可能看起来像这样:

import scala.actors.Actor

case class Sum(x: Int, y: Int)

class SumActor extends Actor {
def act = {
loop {
receive {
case (Sum(x,y), receiver: Actor) => receiver ! x+y
}
}
}
}

class Receiver extends Actor {
def act = {
loop {
receive {
case x: Int => println("Received: " + x)
}
}
}
}

val sumActor = new SumActor
val receiver = new Receiver

sumActor.start
receiver.start

sumActor ! Sum(3,4) -> receiver

您还应该看看 Akka ,因为它将在未来的 Scala 版本中取代 Scala Actor,并且功能更强大。但要了解 Actor 的基础知识,从 Scala Actor 开始就足够了。

关于scala - 在scala中将值从一个 Actor 传递给另一个 Actor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12274999/

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