Scoop API

scoop:scoop.concurrent:0.1.0

src/wait_completion.scoop

Selected production source · src/wait_completion.scoop

1package scoop.concurrent
3import scoop.collections.ArrayDeque
5// Collect while locked, then deliver every selected result outside the lock.
6internal class WaitNotifications {
7 private val actions = ArrayDeque<() -> Unit>()
9 internal fun add(action: () -> Unit) {
10 actions.addLast(action)
11 }
13 internal fun deliver() {
14 var failure: Throwable? = None
15 while (actions.size > 0L) {
16 val action = actions.removeFirst()
17 try {
18 action()
19 }
20 catch (error: Throwable) {
21 if (!waitPresent(failure))
22 failure = Some(error)
23 }
24 }
25 when (failure) {
26 case Some(val error) -> throw error
27 case None -> {}
28 }
29 }
32// This is not an independent arbiter: its owner holds the same lock as the queues.
33internal class PendingResume<T>(continuation: Continuation<T>) {
34 private var continuation: Continuation<T>? = Some(continuation)
35 private var cancellation: Disposable? = None
37 internal val isPending: Boolean get() = waitPresent(continuation)
39 internal fun bind(registration: Disposable?, notifications: WaitNotifications) {
40 if (isPending)
41 cancellation = registration
42 else
43 when (registration) {
44 case Some(val listener) -> notifications.add { listener.dispose() }
45 case None -> {}
46 }
47 }
49 internal fun detachCancellation(notifications: WaitNotifications) {
50 when (cancellation) {
51 case Some(val listener) -> notifications.add { listener.dispose() }
52 case None -> {}
53 }
54 cancellation = None
55 }
57 internal fun succeed(value: T, notifications: WaitNotifications) {
58 val target = continuation!!
59 continuation = None
60 detachCancellation(notifications)
61 notifications.add { target.resume(value) }
62 }
64 internal fun fail(error: Throwable, notifications: WaitNotifications) {
65 val target = continuation!!
66 continuation = None
67 detachCancellation(notifications)
68 notifications.add { target.resumeWithException(error) }
69 }