Scoop API

scoop:scoop.concurrent:0.1.0

src/coroutine_queue.scoop

Selected production source · src/coroutine_queue.scoop

1package scoop.concurrent
3internal 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.
7internal 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 continue
23 if (next === terminal)
24 return false
25 if (next === last) {
26 if (last.next.compareAndSet(last, node)) {
27 tail.compareAndSet(last, node)
28 return true
29 }
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 continue
42 if (next === terminal)
43 return
44 if (next === last) {
45 if (last.next.compareAndSet(last, terminal))
46 return
47 } 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 continue
60 if (first === last) {
61 if (next === first || next === terminal)
62 return None
63 tail.compareAndSet(last, next)
64 } else
65 if (head.compareAndSet(first, next)) {
66 // Break retired links without recreating the open self-link that
67 // 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 keeps
70 // next alive even if another consumer advances head again during a GC.
71 val work = next.work!!
72 next.work = None
73 return Some(work)
74 }
75 }
76 }
79private class CoroutineQueueNode(var work: CoroutineSubmission?) {
80 val next = AtomicRef<CoroutineQueueNode>(this)