From bf455765be92a342f515a79398950f02f5210b14 Mon Sep 17 00:00:00 2001 From: Vsevolod Tolstopyatov Date: Tue, 23 Oct 2018 11:38:14 +0300 Subject: [PATCH] Improve naming and documentation --- .../src/Dispatched.kt | 16 +++++++++++----- .../kotlinx-coroutines-core-common/src/Yield.kt | 2 +- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/common/kotlinx-coroutines-core-common/src/Dispatched.kt b/common/kotlinx-coroutines-core-common/src/Dispatched.kt index e8bd6581d9..d7f7a97717 100644 --- a/common/kotlinx-coroutines-core-common/src/Dispatched.kt +++ b/common/kotlinx-coroutines-core-common/src/Dispatched.kt @@ -21,10 +21,17 @@ internal object UndispatchedEventLoop { @JvmField internal val threadLocalEventLoop = CommonThreadLocal { EventLoop() } - inline fun execute(continuation: DispatchedContinuation<*>, contState: Any?, mode: Int, doYield: Boolean = false, block: () -> Unit) : Boolean { + /** + * Executes given [block] as part of current event loop, updating related to block [continuation] + * mode and state if continuation is not resumed immediately. + * [doYield] indicates whether current continuation is yielding (to provide fast-path if event-loop is empty). + * Returns `true` if execution of continuation was queued (trampolined) or `false` otherwise. + */ + inline fun execute(continuation: DispatchedContinuation<*>, contState: Any?, mode: Int, + doYield: Boolean = false, block: () -> Unit) : Boolean { val eventLoop = threadLocalEventLoop.get() if (eventLoop.isActive) { - // If we are yielding and queue is empty, yield should be a no-op + // If we are yielding and queue is empty, we can bail out as part of fast path if (doYield && eventLoop.queue.isEmpty) { return false } @@ -234,11 +241,10 @@ internal interface DispatchedTask : Runnable { } } -internal fun DispatchedContinuation.yield(): Boolean { - return UndispatchedEventLoop.execute(this, Unit, MODE_CANCELLABLE, true) { +internal fun DispatchedContinuation.yieldUndispatched(): Boolean = + UndispatchedEventLoop.execute(this, Unit, MODE_CANCELLABLE, doYield = true) { run() } -} internal fun DispatchedTask.dispatch(mode: Int = MODE_CANCELLABLE) { val delegate = this.delegate diff --git a/common/kotlinx-coroutines-core-common/src/Yield.kt b/common/kotlinx-coroutines-core-common/src/Yield.kt index fde3391919..78ab27fb87 100644 --- a/common/kotlinx-coroutines-core-common/src/Yield.kt +++ b/common/kotlinx-coroutines-core-common/src/Yield.kt @@ -20,7 +20,7 @@ public suspend fun yield(): Unit = suspendCoroutineUninterceptedOrReturn sc@ { u context.checkCompletion() val cont = uCont.intercepted() as? DispatchedContinuation ?: return@sc Unit if (!cont.dispatcher.isDispatchNeeded(context)) { - return@sc if (cont.yield()) COROUTINE_SUSPENDED else Unit + return@sc if (cont.yieldUndispatched()) COROUTINE_SUSPENDED else Unit } cont.dispatchYield(Unit) COROUTINE_SUSPENDED