Skip to content

Instantly share code, notes, and snippets.

@diogoaurelio
Last active September 28, 2016 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diogoaurelio/da469594752ac4296440645930d4846b to your computer and use it in GitHub Desktop.
Save diogoaurelio/da469594752ac4296440645930d4846b to your computer and use it in GitHub Desktop.
dummy_scala_thread_deadlock_avoid_example.scala
package parallelProg.week1
object Example0501 extends App {
// Resolving deadlocks: acquire resources in the same order
class Account(var amount:Int = 0, val name:String) {
private val x = new AnyRef {}
private var uidCount = 0L
val uid = getUniqueId()
private def lockAndTransfer(target: Account, n: Int) = {
this.synchronized {
target.synchronized {
this.amount -= n
target.amount += n
println(this.name +".amount " +this.amount)
println(n)
println(target.name +".amount " +target.amount)
println(this.amount)
Thread.sleep(2000)
}
}
}
def getUniqueId():Long = x.synchronized {
uidCount +=1
uidCount
}
def transfer(target:Account, n:Int) = {
if(this.uid < target.uid) this.lockAndTransfer(target, n)
else target.lockAndTransfer(this, -n)
}
}
def startThread(a: Account, b:Account, n:Int):Thread = {
val t = new Thread {
override def run: Unit = {
for(i <- 0 until n) {
val amount = i+1
println("Transfering: " +amount + "€ from "+ a.name +" (with uid: "
+ a.uid +") to " + b.name + " (with uid: " + b.uid+")")
a.transfer(b, 1)
}
}
}
t.start()
t
}
val a3 = new Account(50, "C")
a3.amount +=5
println("A3 " + a3.amount)
val a1 = new Account(50, "A")
val a2 = new Account(50, "B")
val t = startThread(a1, a2, 1)
val s = startThread(a2, a1, 5)
t.join()
s.join()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment