scoop:scoop.concurrent:0.1.0
src/coroutine_queue.scoop
Selected production source · src/coroutine_queue.scoop
1
package scoop.concurrent3
internal struct CoroutineSubmission(val affinity: AtomicInt, val work: CoroutineWork)5
// Michael-Scott FIFO. A self-link represents the unpublished end of the chain.6
// GC keeps all observed nodes alive; nodes are never reused or manually reclaimed.7
internal class CoroutineQueue private constructor(initial: CoroutineQueueNode) {8
private val head = AtomicRef<CoroutineQueueNode>(initial)9
private val tail = AtomicRef<CoroutineQueueNode>(initial)10
private val terminal = CoroutineQueueNode(None)12
internal companion object {13
internal fun create(): CoroutineQueue = CoroutineQueue(CoroutineQueueNode(None))14
}16
internal fun tryPut(work: CoroutineSubmission): Boolean {17
val node = CoroutineQueueNode(Some(work))18
while (true) {19
val last = tail.load()20
val next = last.next.load()21
if (last !== tail.load())22
continue23
if (next === terminal)24
return false25
if (next === last) {26
if (last.next.compareAndSet(last, node)) {27
tail.compareAndSet(last, node)28
return true29
}30
} else {31
tail.compareAndSet(last, next)32
}33
}34
}36
internal fun close() {37
while (true) {38
val last = tail.load()39
val next = last.next.load()40
if (last !== tail.load())41
continue42
if (next === terminal)43
return44
if (next === last) {45
if (last.next.compareAndSet(last, terminal))46
return47
} else {48
tail.compareAndSet(last, next)49
}50
}51
}53
internal fun take(): CoroutineSubmission? {54
while (true) {55
val first = head.load()56
val last = tail.load()57
val next = first.next.load()58
if (first !== head.load())59
continue60
if (first === last) {61
if (next === first || next === terminal)62
return None63
tail.compareAndSet(last, next)64
} else65
if (head.compareAndSet(first, next)) {66
// Break retired links without recreating the open self-link that67
// a producer with an old tail snapshot could still compare against.68
first.next.store(terminal)69
// Only the successful consumer reads this payload. Its local root keeps70
// next alive even if another consumer advances head again during a GC.71
val work = next.work!!72
next.work = None73
return Some(work)74
}75
}76
}77
}79
private class CoroutineQueueNode(var work: CoroutineSubmission?) {80
val next = AtomicRef<CoroutineQueueNode>(this)81
}