Skip to content

Instantly share code, notes, and snippets.

@snim2
Created February 6, 2012 11:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snim2/1751700 to your computer and use it in GitHub Desktop.
Save snim2/1751700 to your computer and use it in GitHub Desktop.
Simple Scala examples using synchronized.
import scala.collection.mutable._
class WorkerBee2 (val iterations : Int, var bins : ArrayBuffer[Int]) extends Runnable {
def run() : Unit = {
for(i <- 0 until iterations) {
for (j <- 0 until bins.length) {
// This compiles but misses some iterations:
bins.update(j, bins(j) + 1)
}
}
}
}
object SyncBufferExample {
val iter = 100000
val bins = new ArrayBuffer[Int] with SynchronizedBuffer[Int]
for(i<-0 until 256) bins += 0
def do_work() : Unit = {
val g = new ThreadGroup("WorkerBees")
val t1 = new Thread(g, new WorkerBee2(iter / 2, bins))
val t2 = new Thread(g, new WorkerBee2(iter / 2, bins))
t1.start
t2.start
t1.join
t2.join
}
def verify_work() : Unit = {
var invalid = 0
for (i <- 0 until 256) {
if (bins(i) != iter)
invalid += (iter - bins(i))
}
if (invalid == 0)
println("Bins are valid.")
else
printf("Bins are NOT valid. %d iterations missing.\n", invalid)
}
def main(args: Array[String]) : Unit = {
do_work
verify_work
}
}
class WorkerBee (val iterations : Int, var bins : Array[Int]) extends Runnable {
def update(index: Int) : Unit = synchronized {
bins(index) += 1
}
def run() : Unit = {
for(i <- 0 until iterations) {
for (j <- 0 until bins.length) {
/* // This works:
bins.synchronized {
bins(j) += 1
}
*/
// This compiles but misses some iterations:
this.synchronized {
bins(j) += 1
}
/* // This compiles but misses some iterations:
update(j)
*/
}
}
}
}
object SyncExample {
val iter = 100000
val bins : Array[Int] = new Array[Int](256)
for (i <- 0 until bins.length) bins(i) = 0
def do_work() : Unit = {
val g = new ThreadGroup("WorkerBees")
val t1 = new Thread(g, new WorkerBee(iter / 2, bins))
val t2 = new Thread(g, new WorkerBee(iter / 2, bins))
t1.start
t2.start
t1.join
t2.join
}
def verify_work() : Unit = {
var invalid = 0
for (i <- 0 until bins.length) {
if (bins(i) != iter) {
invalid += (iter - bins(i))
}
}
if (invalid == 0)
println("Bins are valid.")
else
printf("Bins are NOT valid. %d iterations missing.\n", invalid)
}
def main(args: Array[String]) : Unit = {
do_work
verify_work
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment