scoop:scoop.concurrent:0.1.0
src/wait_completion.scoop
Selected production source · src/wait_completion.scoop
1
package scoop.concurrent3
import scoop.collections.ArrayDeque5
// Collect while locked, then deliver every selected result outside the lock.6
internal 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? = None15
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 error27
case None -> {}28
}29
}30
}32
// This is not an independent arbiter: its owner holds the same lock as the queues.33
internal class PendingResume<T>(continuation: Continuation<T>) {34
private var continuation: Continuation<T>? = Some(continuation)35
private var cancellation: Disposable? = None37
internal val isPending: Boolean get() = waitPresent(continuation)39
internal fun bind(registration: Disposable?, notifications: WaitNotifications) {40
if (isPending)41
cancellation = registration42
else43
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 = None55
}57
internal fun succeed(value: T, notifications: WaitNotifications) {58
val target = continuation!!59
continuation = None60
detachCancellation(notifications)61
notifications.add { target.resume(value) }62
}64
internal fun fail(error: Throwable, notifications: WaitNotifications) {65
val target = continuation!!66
continuation = None67
detachCancellation(notifications)68
notifications.add { target.resumeWithException(error) }69
}70
}