1- <!-- - INCLUDE .*/example-([a-z]+)-([0-9 ]+)\.kt
1+ <!-- - INCLUDE .*/example-([a-z]+)-([0-9a-z ]+)\.kt
22/*
33 * Copyright 2016-2017 JetBrains s.r.o.
44 *
@@ -1549,7 +1549,7 @@ but others are unique.
15491549Let us launch a thousand coroutines all doing the same action thousand times (for a total of a million executions).
15501550We'll also measure their completion time for further comparisons:
15511551
1552- <!-- - INCLUDE .*/example-sync-([0-9 ]+).kt
1552+ <!-- - INCLUDE .*/example-sync-([0-9a-z ]+).kt
15531553import kotlin.coroutines.experimental.CoroutineContext
15541554import kotlin.system.measureTimeMillis
15551555-->
@@ -1582,7 +1582,7 @@ suspend fun massiveRun(context: CoroutineContext, action: suspend () -> Unit) {
15821582}
15831583```
15841584
1585- <!-- - INCLUDE .*/example-sync-([0-9 ]+).kt -->
1585+ <!-- - INCLUDE .*/example-sync-([0-9a-z ]+).kt -->
15861586
15871587We start with a very simple action that increments a shared mutable variable using
15881588multi-threaded [ CommonPool] context.
@@ -1608,6 +1608,29 @@ Counter =
16081608What does it print at the end? It is highly unlikely to ever print "Counter = 1000000", because a thousand coroutines
16091609increment the ` counter ` concurrently from multiple threads without any synchronization.
16101610
1611+ > Note: if you have an old system with 2 or fewer CPUs, then you _ will_ consistently see 1000000, because
1612+ ` CommonPool ` is running in only one thread in this case. To reproduce the problem you'll need to make the
1613+ following change:
1614+
1615+ ``` kotlin
1616+ val mtContext = newFixedThreadPoolContext(2 , " mtPool" ) // explicitly define context with two threads
1617+ var counter = 0
1618+
1619+ fun main (args : Array <String >) = runBlocking<Unit > {
1620+ massiveRun(mtContext) { // use it instead of CommonPool in this sample and below
1621+ counter++
1622+ }
1623+ println (" Counter = $counter " )
1624+ }
1625+ ```
1626+
1627+ > You can get full code [ here] ( kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-01b.kt )
1628+
1629+ <!-- - TEST LINES_START
1630+ Completed 1000000 actions in
1631+ Counter =
1632+ -->
1633+
16111634### Volatiles are of no help
16121635
16131636There is common misconception that making a variable ` volatile ` solves concurrency problem. Let us try it:
0 commit comments