Scala program exiting before the execution and completion of all Scala Actor messages being sent. How to stop this?

谁说胖子不能爱 提交于 2019-12-08 04:53:08

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/5256824/scala-program-exiting-before-the-execution-and-completion-of-all-scala-actor-mes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!