所以我想写一些看似阻塞的网络代码,而不是真正阻塞一个线程。我将通过网络发送一些数据,并有一个响应“队列”,这些响应将通过网络返回。我写了一个非常简单的概念证明,灵感来自此处的演员教程中的生产者/消费者示例: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());
}
有没有办法在不使用接收的情况下做到这一点,从而使其无线程?