質問

I have a block of code (as shown below) and I want to make it work concurrently in Scala.

    for(i <- 0 until ca1.length){
      for(j <- 0 until ca2.length){
        val afpchain = algorithm.align(ca1(i), ca2(j))
        afpchain.setName1(label1(i))
        afpchain.setName2(label2(j))
        println(label1(i) + " " + label2(j) + afpchain.getChainRmsd + " " + afpchain.getCalculationTime )
        results.write(label1(i) + " " + label2(j) + " " + afpchain.getChainRmsd + "\n")
        val num1 = new Number(j+1,i+1,afpchain.getChainRmsd(),Format)
        sheet.addCell(num1)
      }
    } 

First of all I would like to know if it is possible. So far only concurrent programming examples I have seen are about chat rooms, messages and rather simpler stuff but this block covers bunch of methods that do numerical operations (i.e. align, getChainRmsd and also ca1 and ca2 are ArrayBuffers of Double coordinate values). What would you advise me and how should I write the code?

Many thanks in advance!

役に立ちましたか?

解決

hmm.... lets say you have an actor that, for each message, spawns a worker actor and calculates the Number for you (and whatever else you need that is parallelizable), which you can query with something like:

val theNum = ask(myActor, new MyMessage(i, j))

MyMessage is just a case class you define in the companion object to MyActor:

case class MyMessage(i: Int, j: Int)

ok, that's nice, now we can do (off the top of my head, may have bugs):

val myNums = 
  for(i <- 0 until ca1.length) yield {
    for(j <- 0 until ca2.length) yield {
      theNum <- ask(myActor, new MyMessage(i, j)).mapTo[Number]       
    }
  }

So your results can be grabbed thusly: (using Await for simplicity, not because I like it):

val result = Await.result(myNums, 10 seconds).flatten.asInstanceOf[Seq[Number]]

Now you'll want to foreach over the result, do your printing/logging and adding of numbers to your "sheet" (whatever that is) -- assuming you didn't take care of that in the actor (depends on what your sheet is and what you need, I suppose).

Note: you could also make myActor a router by doing something like:

val myActor = context.actorOf(Props[MyActor].withRouter( RoundRobinRouter(nrOfInstances = 10))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top