Note that there are some explanatory texts on larger screens.

plurals
  1. POActor that waits for completing all jobs in children before exit
    primarykey
    data
    text
    <p>Can't figure out how to resolve following problem: I have a few actors (workers) that execute tasks in some way when they recieve (I mean react) them. A main actor (foreman) controls this process and can recieve task to stop work. In this case main actor must stop creating new tasks and wait when workers will finish all existing tasks and only then main actor should exit.</p> <pre><code>import actors.Actor import actors.Actor._ class Foreman extends Actor{ val workerA = new WorkerA val workerB = new WorkerB val workerC = new WorkerC self.link(workerA) self.link(workerB) self.link(workerC) def act{ workerA.start workerB.start workerC.start // adding tasks to workers somehow //... loop{ case ResultOfTask(res) =&gt; //... case Stop =&gt; //workers mustn't immediately stop but must finish their tasks and then exit case ProductionAccident =&gt; //... } } } case class Task(activity:String) case class ResultOfTask(result:String) trait Worker extends Actor{ def act{ loop{ react{ case Task(activity) =&gt; sender ! processTask(activity) } } } def processTask(activity:String):ResultOfTask } </code></pre> <p>To solve this I wrote following code:</p> <pre><code>def condition = workerA.getState!=State.Suspended &amp;&amp; workerB.getState!=State.Suspended &amp;&amp; workerC.getState!=State.Suspended &amp;&amp; mailboxSize == 0 case Stop =&gt; { if(condition) exit("sweet dreams") else continue } </code></pre> <p>to check if main actor should exit. Another variant to have counder in "Worker" trait, increment it when worker recieves message and decrement when it reponses.</p> <pre><code>trait Worker extends Actor { private var count = 0 def act { loop{ react{ case Task(activity) =&gt; { count += 1 sender ! processTask(activity) count -= 1 } } } } def hasDoneAllTasks = count == 0 def processTask(activity: String): ResultOfTask } </code></pre> <p>And "condition" function in "Foreman" will be</p> <pre><code>def condition = workerA.hasDoneAllTasks &amp;&amp; workerB.hasDoneAllTasks &amp;&amp; workerC.hasDoneAllTasks &amp;&amp; mailboxSize == 0 </code></pre> <p>I hope there are better solutions and you will propose them.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload