/
ConcurrentIntList.scala
80 lines (69 loc) · 1.79 KB
/
ConcurrentIntList.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* scala-stm - (c) 2009-2010, Stanford University, PPL */
package scala.concurrent.stm.examples
import scala.concurrent.stm._
class ConcurrentIntList {
private class Node(val elem: Int, prev0: Node, next0: Node) {
val isHeader = prev0 == null
val prev = Ref(if (isHeader) this else prev0)
val next = Ref(if (isHeader) this else next0)
}
private val header = new Node(-1, null, null)
def addLast(elem: Int) {
atomic { implicit txn =>
val p = header.prev()
val newNode = new Node(elem, p, header)
p.next() = newNode
header.prev() = newNode
}
}
def addLast(e1: Int, e2: Int, elems: Int*) {
atomic { implicit txn =>
addLast(e1)
addLast(e2)
elems foreach { addLast(_) }
}
}
//def isEmpty = atomic { implicit t => header.next() == header }
def isEmpty = header.next.single() == header
def removeFirst(): Int = atomic { implicit txn =>
val n = header.next()
if (n == header)
retry
val nn = n.next()
header.next() = nn
nn.prev() = header
n.elem
}
def maybeRemoveFirst(): Option[Int] = {
atomic { implicit txn =>
Some(removeFirst())
} orAtomic { implicit txn =>
None
}
}
override def toString: String = {
atomic { implicit txn =>
val buf = new StringBuilder("ConcurrentIntList(")
var n = header.next()
while (n != header) {
buf ++= n.elem.toString
n = n.next()
if (n != header) buf ++= ","
}
buf ++= ")" toString
}
}
}
object ConcurrentIntList {
def select(stacks: ConcurrentIntList*): (ConcurrentIntList, Int) = {
atomic { implicit txn =>
for (s <- stacks) {
s.maybeRemoveFirst() match {
case Some(e) => return (s, e)
case None =>
}
}
retry
}
}
}