Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

actor

What's the difference of using loop instead of while(true) while using receive with actors. Loop seems to work much faster, but why, and what's going on under the bonnet?

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

More about context. I'm doing performance tests within simple ping/pong code. And I'm using receive.

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 performs better with loop.

Thanks

like image 834
Zerdush Avatar asked Jan 26 '11 11:01

Zerdush


2 Answers

The while/receive loop blocks a thread, whereas the loop/react construct doesn't. This means the first construct needs one thread per actor, which quickly becomes slow.

According to Haller and Odersky 2006,

An actor that waits in a receive statement is not represented by a blocked thread but by a closure that captures the rest of the actor's computation. The closure is executed once a message is sent to the actor that matches one of the message patterns specied in the receive. The execution of the closure is "piggy-backed" on the thread of the sender. If the receiving closure terminates, control is returned to the sender as if a procedure returns. If the receiving closure blocks in a second receive, control is returned to the sender by throwing a special exception that unwinds the receiver's call stack.

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

like image 145
Fred Foo Avatar answered Nov 11 '22 23:11

Fred Foo


Using loop releases the thread to other tasks, while while doesn't. So, if you are using many actors, the use of loop makes then more efficient. On the other hand, a single actor using while and receive is much faster than one using loop and react (or, for that matter, loop and receive).

like image 45
Daniel C. Sobral Avatar answered Nov 11 '22 21:11

Daniel C. Sobral