Scala程序在执行和完成所有发送的Scala Actor消息之前退出。如何停止这个? [英] Scala program exiting before the execution and completion of all Scala Actor messages being sent. How to stop this?

查看:500
本文介绍了Scala程序在执行和完成所有发送的Scala Actor消息之前退出。如何停止这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个for循环发送我的Scala Actor的消息。 scala演员正在接收
消息并获得处理它们的工作。 actor正在处理cpu和磁盘密集型任务,如解压缩和存储文件。我通过在for循环中的消息传递代码中插入一个延迟 Thread.sleep(200)来推断Actor部分正常工作。

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)
}



,我的问题是程序退出与代码0一旦for循环完成执行。因此阻止我的演员完成那里的工作。我如何解决这个问题?这可能是一个n00b的问题。任何帮助是高度赞赏!

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!

编辑1:
现在解决了我的问题:

Edit 1: This solved my problem for now:

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

这是我最好的吗?

推荐答案

假设你有一个演员,工作。要避免 sleep ,可以创建一个 SyncVar ,并等待它在主线程中初始化:

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

主线程将等待某些值赋给 sv ,然后被唤醒。

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

如果有多个actors,那么你可以有多个 SyncVar ,或者做这样的事情:

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
}

这篇关于Scala程序在执行和完成所有发送的Scala Actor消息之前退出。如何停止这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆