Scala示例:Scala 2.11.7中的spawn函数

3
我正在尝试使用Scala版本2.11.7实现《Scala by Example》书中第17.9节"Workers"。导入语句如下:
import scala.concurrent._, scala.concurrent.ops._

发生了错误 "ops not is member of scala.concurrent"。我进行了谷歌搜索,得知 concurrent.ops 已被弃用,应该改为使用 future,请将导入语句改为:
import scala.concurrent._, scala.concurrent.Future._

整个班级的来源:
import scala.concurrent._
import scala.concurrent.Future._

class ComputeServer(n: Int) {

  private abstract class Job {
    type T
    def task: T
    def res(x: T)
  }

  private val openJobs = new Channel[Job]()

  private def processor(i: Int) {
    while(true) {
      val job = openJobs.read
      job.res(job.task)
    }
  }

  def future[A](p: => A): () => A = {
    val reply = new SyncVar[A]()
    openJobs.write{
      new Job{
        type T = A
        def task = p
        def res(x: A) = reply.put(x)
      }
    }
    () => reply.get
  }

  spawn(replicate(0, n){processor})
}

但是在这一行中出现了错误:spawn(replicate(0, n){processor})
not found: value spawn
not found: value replicate
missing arguments for method processor in class ComputeServer; follow this method with `_' if you want to treat it as a partially applied function

“在2.11.7版本中,'spawn'、'replicate'和'processor function'是什么?”

1
Spawn被用来创建一个包含给定代码的线程。你可以使用Future { .... // code } 来实现。我不知道replicate,但你可以在这里找到源代码:http://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_7_2_final/src/library/scala/concurrent/ops.scala?view=markup 这个API已经非常老了。 - Łukasz
我在你的URL中找到了属于ops对象的复制函数。 - code4f
当然你找到了,这就是我给你URL的原因...但它是过时的资源。 - Łukasz
1个回答

1

可以像这样创建 spawn 方法:

def spawn(p: => Unit) {
   val t = new Thread() { override def run() = p }
   t.start()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接