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

萝らか妹 提交于 2019-12-06 16:32:12

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