scala - What is the purpose of an empty loop in this volatile var example? -


code:

  class page(val txt: string, var position: int)    val rand = new random()   object volatile {     val pages = for(i <- 1 5) yield new page("na" * rand.nextint(1000) + " batman!", -1)     @volatile var found = false     (p <- pages) yield thread {       var = 0       while (i < p.txt.length && !found) if (p.txt(i) == '!') {         p.position =         found = true       } else += 1       while(!found) {}       log(s"results: ${pages.map(_.position)}")     }   } 

what purpose of empty loop while(!found) {}?

the first loop: while (i < p.txt.length && !found) has 2 conditions stopping: when search space exhausted, or when match found. note found variable used in multiple threads: thread {...} presumably spawns new thread.

so there several possibilities how threads' loops can play out:

  • the thread finds '!' , sets found. first loop breaks, second doesn't execute.
  • another thread sets found. first loop breaks, second doesn't execute.
  • all characters searched. first loop breaks, second executes until thread finds '!'.

the third 1 1 forgot. consequence results logged once loops finished.


granted, can't tell why code looks does: each thread, separately prints results pages, i.e. if there n pages, n^2 results logged. also, threads access shared object without synchronization. if goal find 1 exclamation mark, code fails. anyway, these seem separate issues.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -