1
- <!-- - INCLUDE .*/example-([a-z]+)-([0-9 ]+)\.kt
1
+ <!-- - INCLUDE .*/example-([a-z]+)-([0-9a-z ]+)\.kt
2
2
/*
3
3
* Copyright 2016-2017 JetBrains s.r.o.
4
4
*
@@ -1549,7 +1549,7 @@ but others are unique.
1549
1549
Let us launch a thousand coroutines all doing the same action thousand times (for a total of a million executions).
1550
1550
We'll also measure their completion time for further comparisons:
1551
1551
1552
- <!-- - INCLUDE .*/example-sync-([0-9 ]+).kt
1552
+ <!-- - INCLUDE .*/example-sync-([0-9a-z ]+).kt
1553
1553
import kotlin.coroutines.experimental.CoroutineContext
1554
1554
import kotlin.system.measureTimeMillis
1555
1555
-->
@@ -1582,7 +1582,7 @@ suspend fun massiveRun(context: CoroutineContext, action: suspend () -> Unit) {
1582
1582
}
1583
1583
```
1584
1584
1585
- <!-- - INCLUDE .*/example-sync-([0-9 ]+).kt -->
1585
+ <!-- - INCLUDE .*/example-sync-([0-9a-z ]+).kt -->
1586
1586
1587
1587
We start with a very simple action that increments a shared mutable variable using
1588
1588
multi-threaded [ CommonPool] context.
@@ -1608,6 +1608,29 @@ Counter =
1608
1608
What does it print at the end? It is highly unlikely to ever print "Counter = 1000000", because a thousand coroutines
1609
1609
increment the ` counter ` concurrently from multiple threads without any synchronization.
1610
1610
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
+
1611
1634
### Volatiles are of no help
1612
1635
1613
1636
There is common misconception that making a variable ` volatile ` solves concurrency problem. Let us try it:
0 commit comments