Scala 程序在执行和完成发送的所有 Scala Actor 消息之前退出。如何阻止这个?

发布于 2024-10-21 04:53:58 字数 503 浏览 1 评论 0原文

我正在通过 for 循环向 Scala Actor 发送消息。 scala actor 正在接收 消息并开始处理它们。参与者正在处理 CPU 和磁盘密集型任务,例如解压缩和存储文件。我通过在 for 循环中的消息传递代码中添加延迟 Thread.sleep(200) 来推断 Actor 部分工作正常。

for ( val e <- entries ) {
  MyActor ! new MyJob(e)
  Thread.sleep(100)
}

现在,我的问题是,一旦 for 循环完成执行,程序就会以代码 0 退出。从而阻止我的演员完成那里的工作。我该如何克服这个问题?这可能真的是一个n00b问题。非常感谢任何帮助!

编辑1: 这暂时解决了我的问题:

while(MyActor.getState != Actor.State.Terminated)
  Thread.sleep(3000)

这是我能做的最好的事情吗?

I am sending my Scala Actor its messages from a for loop. The scala actor is receiving the
messages and getting to the job of processing them. The actors are processing cpu and disk intensive tasks such as unzipping and storing files. I deduced that the Actor part is working fine by putting in a delay Thread.sleep(200) in my message passing code in the for loop.

for ( val e <- entries ) {
  MyActor ! new MyJob(e)
  Thread.sleep(100)
}

Now, my problem is that the program exits with a code 0 as soon as the for loop finishes execution. Thus preventing my Actors to finish there jobs. How do I get over this? This may be really a n00b question. Any help is highly appreciated!

Edit 1:
This solved my problem for now:

while(MyActor.getState != Actor.State.Terminated)
  Thread.sleep(3000)

Is this the best I can do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心房敞 2024-10-28 04:53:58

假设您有一位演员想要完成其工作。为了避免睡眠,您可以创建一个 SyncVar 并等待它在主线程中初始化:

val sv = new SyncVar[Boolean]

// start the actor
actor {
  // do something
  sv.set(true)
}

sv.take

主线程将等待,直到将某个值分配给 sv< /code>,然后被唤醒。

如果有多个参与者,那么您可以拥有多个 SyncVar,或者执行如下操作:

class Ref(var count: Int)

val numactors = 50
val cond = new Ref(numactors)

// start your actors
for (i <- 0 until 50) actor {
  // do something

  cond.synchronized {
    cond.count -= 1
    cond.notify()
  }
}

cond.synchronized {
  while (cond.count != 0) cond.wait
}

Assume you have one actor you're want to finish its work. To avoid sleep you can create a SyncVar and wait for it to be initialized in the main thread:

val sv = new SyncVar[Boolean]

// start the actor
actor {
  // do something
  sv.set(true)
}

sv.take

The main thread will wait until some value is assigned to sv, and then be woken up.

If there are multiple actors, then you can either have multiple SyncVars, or do something like this:

class Ref(var count: Int)

val numactors = 50
val cond = new Ref(numactors)

// start your actors
for (i <- 0 until 50) actor {
  // do something

  cond.synchronized {
    cond.count -= 1
    cond.notify()
  }
}

cond.synchronized {
  while (cond.count != 0) cond.wait
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文