[英]Scala Actors - using SingleThreadedScheduler with receive
[英]Possible to make a producer/consumer obj in Scala using actors 'threadless' (no receive…)?
所以我想编写一些似乎是阻塞的网络代码,而不是实际阻塞线程。 我将通过线路发送一些数据,并有一个响应的“队列”,将通过网络返回。 我写了一个非常简单的概念证明,灵感来自于这里的演员教程的制作人/消费者示例: 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());
}
有没有办法在不使用接收的情况下执行此操作,从而使其成为无线程?
你可以直接依赖于react
应该阻止和释放线程:
class Connection {
private val act:Actor = actor {
loop {
react {
case r:Request => reply { r }
}
}
}
[...]
我希望你可以使用反应而不是接收,而不是让演员接受像接收那样的线程。 在接收和反应这个问题上有线程。
好的,我在这里描述的是: http : //lampwww.epfl.ch/~odersky/papers/jmlc06.pdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.