Skip to content
Snippets Groups Projects
02-scalaThreadWrapper.scala 1.03 KiB
Newer Older
//    PDF: https://moodle.epfl.ch/pluginfile.php/3175938/mod_folder/content/0/week01-3-Introduction-to-Threads-2-with-Demo.pdf
//  Video: https://mediaspace.epfl.ch/playlist/dedicated/31866/0_c46icdbx/0_zx4gncsb
// Slides: 1-2

package lecture1

/** Wraps a call-by-name argument `toRun` to be run in a separate thread.
  *
  * @param toRun
  *   the expression to run in a separate tread
  */
class ThreadReturning[A](toRun: => A) extends Thread:
  var result: A = _

  override def run(): Unit =
    result = toRun

  def joinMe: A =
    join()
    result

def threadStart[A](toRun: => A): ThreadReturning[A] =
  val t = ThreadReturning(toRun)
  t.start()
  t

def countLots: Long =
  var s, i: Long = 0
  while i < 7 do
    var j: Long = 0
    while j < 900000000 do
      j = j + 1
      s = s + i + j
    i = i + 1
    println(f"Iteration ${i}")
  s

// Run from the SBT shell with `runMain lecture1.scalaThreadWrapper`.
@main def scalaThreadWrapper: Unit =
  val (x, y) = (threadStart(countLots), threadStart(countLots))
  println((x.joinMe, y.joinMe))