What happens when we use a loop instead of while (true) with scala actors?

What is the difference in using a loop instead of while (true) when using a trick with participants. Loop seems to be much faster, but why, and what happens under the hood?

Is there anything bad to using a loop instead of while (true)?

More about the context. I run performance tests as part of simple ping / pong code. And I use receipt.

This is the Ping class:

class ReceivePing( count : Int, pong : Actor ) extends Actor {def act() { var pingsLeft = count - 1 pong ! Start pong ! ReceivePing while(true) { receive { case ReceivePong => if (pingsLeft % 10000 == 0) Console.println("ReceivePing: pong") if (pingsLeft > 0) { pong ! ReceivePing pingsLeft -= 1 } else { Console.println("ReceivePing: stop") pong ! Stop exit() } } }}} 

instead of while (true) it works better with a loop.

thanks

+7
source share
2 answers

Using loop frees the thread for other tasks, while while does not. So, if you use a lot of actors, using loop makes it more efficient. On the other hand, one actor using while and receive is much faster than one using loop and react (or, for that matter, loop and receive ).

+3
source

The while / receive while blocks the flow , while the loop / react does not. This means that the first design requires one thread for each actor, which slows down quickly.

According to Haller and Odersky 2006 ,

An actor who is waiting in a reception for approval is not represented by a locked thread, but by a closure that captures the rest of the calculation. Closing is performed as soon as the message is sent to the actor who corresponds to one of the message templates specified in the reception. Closing "feedback" in the sender thread. If the receiving close completes, control returns as if the procedure had returned. If the receiving trailing blocks are in second reception, control returns to the sender, throwing a special exception that frees the call stack.

(Apparently, they later changed the receive behavior and renamed the old receive to react .)

+4
source

All Articles