https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

TwoClocks

10/07/2018, 6:59 PM
I don't quite understand the contexts. For example, if I remove the runBlocking{} from the following code, it runs fine w/ the "done blocking" running in some random worker thread. But w/ the runBlocking{}, and that block never exits. I'm trying to run all the coroutines the main thread. code :
Copy code
fun main(args : Array<String>) {
    var taskHandle:Continuation<Unit>?=null

    runBlocking { // If I run in this context, this block never exits.

        launch {
            while(true) {
                println("about to block")
                val retVal = suspendCoroutine<Unit> {
                    taskHandle = it;
                }
                println("done blocking.. on thread : ${Thread.currentThread().name}")
            }
        }
        println("done launching")
    }

    println("all coroutines blocked, do work...")

    repeat( 10, {
        Thread.sleep(ThreadLocalRandom.current().nextInt(2000) + 500L)
        taskHandle!!.resume(Unit)
    })
}
d

Dico

10/07/2018, 10:00 PM
Which version of Kotlin/coroutines are you using?
launch
without a scope is deprecated in 1.3, but this should be true in 1.3, not in versions prior to 1.3 and its development builds.
k

krotki

10/07/2018, 10:28 PM
In my understanding of new coroutines in 1.3 - runBlocking provides CoroutineScope, so launch would take scope from it ... also runBlocking uses current thread as executor (if you don't specify another), so launch reuses it.
t

TwoClocks

10/07/2018, 10:55 PM
It's just a Idea project, so it's a little hard to tell the kotlin version. I think it 1.2.70, and version 0.30.0 of coroutines
for this code, the runBlocking { } block never exits. It seems like the coroutines demand at least one thread of their own.
k

krotki

10/08/2018, 7:41 AM
runBlocking will wait for all child coroutines to finish. In your launch you have while(true) so it newer exits.
form doc:
Copy code
* Runs new coroutine and **blocks** current thread _interruptibly_ until its completion.
 * This function should not be used from coroutine. It is designed to bridge regular blocking code
 * to libraries that are written in suspending style, to be used in `main` functions and in tests.
 *
 * The default [CoroutineDispatcher] for this builder in an internal implementation of event loop that processes continuations
 * in this blocked thread until the completion of this coroutine.
 * See [CoroutineDispatcher] for the other implementations that are provided by `kotlinx.coroutines`.
 *
 * When [CoroutineDispatcher] is explicitly specified in the [context], then the new coroutine runs in the context of
 * the specified dispatcher while the current thread is blocked. If the specified dispatcher is an event loop of another `runBlocking`,
 * the this invocation uses an outer event loop.
t

TwoClocks

10/08/2018, 7:09 PM
So how to I run all the coroutines on the main thread?
3 Views