-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTreiberStackWithElimination.kt
More file actions
53 lines (42 loc) · 1.88 KB
/
TreiberStackWithElimination.kt
File metadata and controls
53 lines (42 loc) · 1.88 KB
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
package day1
import kotlinx.atomicfu.*
import java.util.concurrent.*
class TreiberStackWithElimination<E> : Stack<E> {
private val stack = TreiberStack<E>()
// TODO: Try to optimize concurrent push and pop operations,
// TODO: synchronizing them in an `eliminationArray` cell.
private val eliminationArray = atomicArrayOfNulls<Any?>(ELIMINATION_ARRAY_SIZE)
override fun push(element: E) {
if (tryPushElimination(element)) return
stack.push(element)
}
private fun tryPushElimination(element: E): Boolean {
TODO("Implement me!")
// TODO: Choose a random cell in `eliminationArray`
// TODO: and try to install the element there.
// TODO: Wait `ELIMINATION_WAIT_CYCLES` loop cycles
// TODO: in hope that a concurrent `pop()` grabs the
// TODO: element. If so, clean the cell and finish,
// TODO: returning `true`. Otherwise, move the cell
// TODO: to the empty state and return `false`.
}
override fun pop(): E? = tryPopElimination() ?: stack.pop()
private fun tryPopElimination(): E? {
TODO("Implement me!")
// TODO: Choose a random cell in `eliminationArray`
// TODO: and try to retrieve an element from there.
// TODO: On success, return the element.
// TODO: Otherwise, if the cell is empty, return `null`.
}
private fun randomCellIndex(): Int =
ThreadLocalRandom.current().nextInt(eliminationArray.size)
companion object {
private const val ELIMINATION_ARRAY_SIZE = 2 // Do not change!
private const val ELIMINATION_WAIT_CYCLES = 1 // Do not change!
// Initially, all cells are in EMPTY state.
private val CELL_STATE_EMPTY = null
// `tryPopElimination()` moves the cell state
// to `RETRIEVED` if the cell contains element.
private val CELL_STATE_RETRIEVED = Any()
}
}