I’m trying to set up a minimal example that gives ...
# coroutines
v
I’m trying to set up a minimal example that gives race conditions. Any suggestions? The best I’ve got is this https://pl.kotl.in/4yU_BS_qv but it has a quirk that I don’t understand. (Question embedded in the code snippet).
b
Because
GlobalScope
is not the same as the scope provided by
runBlocking
. Your
runBlocking
parent scope only has the main thread, so only one coroutine will run at a time accessing the
counter
from the same thread, so there's no shared mutable state going on.
GlobalScope
, on the other-hand, has multiple threads available to it, which means multiple of your `massiveRun`'s job will run in parallel, causing overwriting of mutable state
You would want to do
Copy code
runBlocking {
    launch(Dispatchers.Default) {
        // paste the function body
    }.join()
}
v
Excellent explanation! Thank you.
b
Immediately joining on a job you created with launch is generally a code smell that can be replaced with
Copy code
runBlocking {
    withContext(Dispatchers.Default) {
        // paste the function body
    }
}
🙏 1
happy to help! 🎉
v
Awesome, that’s a great tip! Based on your answer I also found this in the documentation (for anyone reading this that wants more): https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html
l
Why not just use
suspend fun main(): Unit = coroutineScope { … }
? It uses
Dispatchers.Default
.
👍 2
🤔 1
b
That's good to know @louiscad! I would say it's a bit harder to know when reading the code though without background knowledge
l
Here's a little part of my background @bdawg.io: The first time I noticed it was during my first English talk (I'm French native, we are renowned for our foreign languages skill 😅), when my demo using 2 concurrent
Thread.sleep
failed to show any difference with `delay`… It was the first I used it as it was new in 1.3RC. I natively thought it'd be like
runBlocking
. Found the answer and fixed it during Q&A, fortunately.