2

所以我想写一些看似阻塞的网络代码,而不是真正阻塞一个线程。我将通过网络发送一些数据,并有一个响应“队列”,这些响应将通过网络返回。我写了一个非常简单的概念证明,灵感来自此处的演员教程中的生产者/消费者示例:http ://www.scala-lang.org/node/242

问题是,使用接收似乎占用了一个线程,所以我想知道是否无论如何不占用一个线程并且仍然获得“阻塞感”。这是我的代码示例:

import scala.actors.Actor._;
import scala.actors.Actor;

case class Request(val s:String);

case class Message(val s:String);

class Connection  {
  private val act:Actor = actor {
     loop {
      react {
        case m:Message =>  receive { case r:Request => reply { m } }
      } 
    }
}

  def getNextResponse(): Message = {
    return (act !? new Request("get")).asInstanceOf[Message];
  }

  //this would call the network layer and send something over the wire
  def doSomething() {
    generateResponse();
  }

  //this is simulating the network layer getting some data back 
  //and sending it to the appropriate Connection object
  private def generateResponse() {
   act ! new Message("someData");
   act ! new Message("moreData");    
   act ! new Message("even more data");
  }

}


object runner extends Application {
 val conn = new Connection(); 
    conn.doSomething();
    println( conn.getNextResponse());
    println(conn.getNextResponse());
    println(conn.getNextResponse());
}

有没有办法在不使用接收的情况下做到这一点,从而使其无线程?

4

2 回答 2

4

您可以直接依赖react哪个应该阻塞释放线程:

class Connection  {
  private val act:Actor = actor {
    loop {
      react {
        case r:Request => reply { r }
      } 
    }
  }
[...]
于 2009-12-10T22:30:22.420 回答
3

我希望您可以使用 react 而不是接收,并且不会像接收那样让参与者占用线程。在receive vs react有关于这个问题的线程。

于 2009-12-10T21:22:13.477 回答