scoop:scoop.core:0.1.0
src/coroutine_blocking.scoop
Selected production source · src/coroutine_blocking.scoop
1
/**2
* Suspends while a synchronous managed function runs on the current executor's blocking pool.3
* Cancellation can withdraw a queued call. Once the function starts, its actual result or failure4
* is delivered after cleanup, even when the caller's job has been cancelled. Requires an executor.5
*/6
public suspend fun <T> blocking(block: () -> T): T =7
when (currentCoroutineExecutorOrNone()) {8
case Some(val executor) -> executor.blocking(block)9
case None -> throw IllegalStateException(Some("blocking requires a coroutine executor"))10
}12
/**13
* Runs a synchronous managed function on this executor and returns to the caller's execution.14
* The function inherits context bindings and can allocate managed values, but cannot suspend.15
* Cancellation and result delivery follow the same rules as the implicit-executor blocking call.16
*/17
public suspend fun <T> CoroutineExecutor.blocking(block: () -> T): T {18
ensureActive()19
val task = registerTask(executorParent(this, currentExecutorTask()))20
return suspendCoroutine<T> {21
continuation ->22
val operation =23
try {24
BlockingOperation<T>(task, BlockingRequest<T>(continuation, block))25
} catch (error: Throwable) {26
task.complete()27
throw error28
}29
operation.submit(currentJobOrNone())30
}31
}33
private enum BlockingOperationState<T> {34
Queued(BlockingRequest<T>)35
Running36
// Cancellation notification and shell retirement can finish in either order.37
Cancelling(Boolean)38
Cancelled39
Finished40
}42
private class BlockingOperation<T>(43
private val task: ExecutorTask,44
request: BlockingRequest<T>45
): BlockingWork {46
private val lock = CoroutineLock()47
private var state: BlockingOperationState<T> = BlockingOperationState.Queued(request)48
private var cancellation: Disposable? = None50
fun submit(job: Job?) {51
try {52
when (job) {53
case Some(val job) -> {54
val listener = job.invokeOnCancellation { error -> cancel(error) }55
val installed =56
lock.withLock {57
when (state) {58
case BlockingOperationState.Queued(_) -> {59
cancellation = Some(listener)60
true61
}62
else -> false63
}64
}65
if (!installed)66
listener.dispose()67
}68
case None -> {}69
}70
} finally {71
// Even a synchronously cancelled operation retires through its queued shell.72
task.dispatchBlocking(this)73
}74
}76
private fun cancel(error: CancellationException) {77
val claimed: (BlockingRequest<T>, Disposable?)? =78
lock.withLock {79
when (state) {80
case BlockingOperationState.Queued(val request) -> {81
state = BlockingOperationState.Cancelling(false)82
val listener = cancellation83
cancellation = None84
Some((request, listener))85
}86
else -> None87
}88
}89
when (claimed) {90
case Some((val request, val listener)) -> {91
try {92
listener?.dispose()93
request.cancel(error)94
} finally {95
finishCancellation()96
}97
}98
case None -> {}99
}100
}102
private fun finishCancellation() {103
val retired =104
lock.withLock {105
when (state) {106
case BlockingOperationState.Cancelling(val retired) -> {107
state =108
if (retired)109
BlockingOperationState.Finished110
else111
BlockingOperationState.Cancelled112
retired113
}114
else -> throw IllegalStateException(115
Some("blocking cancellation finished twice")116
)117
}118
}119
if (retired)120
task.complete()121
}123
public override fun run() {124
val(request, listener, complete) =125
lock.withLock {126
var complete = true127
val request: BlockingRequest<T>? =128
when (state) {129
case BlockingOperationState.Queued(val request) -> {130
state = BlockingOperationState.Running131
Some(request)132
}133
case BlockingOperationState.Cancelled -> {134
state = BlockingOperationState.Finished135
None136
}137
case BlockingOperationState.Cancelling(false) -> {138
state = BlockingOperationState.Cancelling(true)139
complete = false140
None141
}142
else -> throw IllegalStateException(143
Some("blocking work ran more than once")144
)145
}146
val listener = cancellation147
cancellation = None;148
(request, listener, complete)149
}150
try {151
listener?.dispose()152
request?.run()153
} finally {154
if (complete) {155
lock.withLock { state = BlockingOperationState.Finished }156
task.complete()157
}158
}159
}160
}162
private enum BlockingResult<T> {163
Value(T)164
Failure(Throwable)165
}167
private class BlockingInvocation<T>(private val block: () -> T) {168
private var result: MaybeUninit<BlockingResult<T>> = MaybeUninit<BlockingResult<T>>.uninit()170
fun invoke(): Int {171
val outcome: BlockingResult<T> =172
try {173
BlockingResult.Value(block())174
}175
catch (error: Throwable) {176
BlockingResult.Failure(error)177
}178
result = MaybeUninit<BlockingResult<T>>.initialized(outcome)179
return 0180
}182
fun deliver(continuation: Continuation<T>) {183
@Unsafe184
{185
when (result.assumeInit()) {186
case BlockingResult.Value(val value) -> continuation.resume(value)187
case BlockingResult.Failure(val error) -> continuation.resumeWithException(error)188
}189
}190
}191
}193
private class BlockingRequest<T>(private val continuation: Continuation<T>, block: () -> T) {194
private val invocation = BlockingInvocation<T>(block)195
private val callback = registerCallback()197
private fun registerCallback(): ForeignCallback<(Ptr<Unit>) -> Int> {198
@Unsafe199
{200
return foreignCallback<(Ptr<Unit>) -> Int>(201
{ invocation.invoke() },202
0,203
ForeignCallbackMode.OneShot204
)205
}206
}208
fun cancel(error: CancellationException) {209
@Unsafe210
{211
releaseForeignCallback(callback)212
}213
continuation.resumeWithException(error)214
}216
fun run() {217
@Unsafe218
{219
callback.function(callback.context)220
}221
// Invocation consumes the callback and restores Context before publishing the result.222
invocation.deliver(continuation)223
}224
}