-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTreiberStack.kt
More file actions
33 lines (28 loc) · 871 Bytes
/
TreiberStack.kt
File metadata and controls
33 lines (28 loc) · 871 Bytes
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
package day1
import kotlinx.atomicfu.*
class TreiberStack<E> : Stack<E> {
// Initially, the stack is empty.
private val top = atomic<Node<E>?>(null)
override fun push(element: E) {
// TODO: Make me linearizable!
// TODO: Update `top` via Compare-and-Set,
// TODO: restarting the operation on CAS failure.
val curTop = top.value
val newTop = Node(element, curTop)
top.value = newTop
}
override fun pop(): E? {
// TODO: Make me linearizable!
// TODO: Update `top` via Compare-and-Set,
// TODO: restarting the operation on CAS failure.
val curTop = top.value ?: return null
top.value = curTop.next.value
return curTop.element
}
private class Node<E>(
val element: E,
next: Node<E>?
) {
val next = atomic(next)
}
}