代码之家  ›  专栏  ›  技术社区  ›  Vincent

是否可以使用actors'threadless'(没有接收…)在scala中创建生产者/消费者obj?

  •  2
  • Vincent  · 技术社区  · 16 年前

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

    问题是,使用receive似乎占用了一个线程,所以我想知道是否仍然有不占用一个线程,仍然得到'阻塞的感觉'。这是我的代码示例:

    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());
    }
    

    有没有一种方法可以在不使用receive的情况下做到这一点,从而使它变得无螺纹?

    3 回复  |  直到 16 年前
        1
  •  4
  •   paradigmatic    16 年前

    你可以直接依靠 react 哪个应该挡住 和 松开螺纹:

    class Connection  {
      private val act:Actor = actor {
        loop {
          react {
            case r:Request => reply { r }
          } 
        }
      }
    [...]
    
        2
  •  3
  •   Community Mohan Dere    9 年前

    我希望您可以使用react而不是receive,并且不要让actor像receive那样占用线程。有关于这个问题的线索在 receive vs react .

        3
  •  1
  •   Vincent    16 年前

    好吧,我真正想做的是在这里描述: http://lampwww.epfl.ch/~odersky/papers/jmlc06.pdf

    推荐文章