Skip to content
Snippets Groups Projects
04-OnePlaceBufferDemo.scala 740 B
Newer Older
Matt Bovel's avatar
Matt Bovel committed
package lecture6

import scala.concurrent.ExecutionContext
import lecture1.threadStart
Matt Bovel's avatar
Matt Bovel committed

class OnePlaceBuffer[Elem]:
  var elem: Elem = _
  var full = false
  def put(e: Elem): Unit = this.synchronized {
    while full do wait()
    elem = e
    full = true
    log(f"Put $e in the buffer")
    notifyAll()
  }
  def get(): Elem = this.synchronized {
    while !full do wait()
    full = false
    notifyAll()
    log(f"Got $elem from the buffer")
    elem
  }

@main def OnePlaceBufferDemo =
  val buffer = OnePlaceBuffer[Int]()
  val getThreads = for i <- 0 until 10 yield threadStart { buffer.get() }
  val putThreads = for i <- 0 until 10 yield threadStart { buffer.put(i) }
Matt Bovel's avatar
Matt Bovel committed
  putThreads.foreach(_.join())
  getThreads.foreach(_.join())