F
F
foonfyrick2020-12-24 07:59:17
Kotlin
foonfyrick, 2020-12-24 07:59:17

Why, when increasing the number in coroutines, the number sometimes has a different value?

1) Why, if I write this code, then in runBlocking I sometimes change the value of the variable, sometimes it is 20,000, and sometimes a little less, but if I delete the entire CoroutineScope and leave only runBlocking, then my variable value is always 10,000 2 )
And why in general in the first case, when there is both coroutineScope and runBlockin, my variable tends to 20,000 in both cases, and not to 10,000? It feels like the repetitions are trying to add up, but in runBlockin they add up crookedly.

The code:

val int = AtomicInteger()

            CoroutineScope(Dispatchers.IO).launch {
                repeat(100) {
                    launch {
                        repeat(100) {
                            int.incrementAndGet()
                        }
                    }
                }
                Log.e("@@@ CoroutineScope @@@", int.toString())
            }


        runBlocking {
            withContext(Dispatchers.IO) {
                repeat(100) {
                    launch {
                        repeat(100) {
                            int.incrementAndGet()
                        }
                    }
                }
            }
            Log.e("@@@ withContext @@@", int.toString())
        }

Screenshots:
5fe4197755730781290596.png
5fe41983af53b758327866.png
5fe41990687c6916381975.png
5fe41999a9975651794145.png
5fe419a800c28053724822.png
5fe419b7642f1997046543.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
koperagen, 2020-12-26
@foonfyrick

Discussed in a comment (: The log is printed before all coroutines have finished incrementing the counter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question