Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | package kotlinx.coroutines.experimental.selects |
| 6 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 7 | import kotlinx.coroutines.experimental.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 8 | import kotlin.coroutines.experimental.* |
Vsevolod Tolstopyatov | 2cdbfd7 | 2018-04-22 18:26:14 +0300 | [diff] [blame] | 9 | import kotlin.test.* |
Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 10 | |
Vsevolod Tolstopyatov | 2cdbfd7 | 2018-04-22 18:26:14 +0300 | [diff] [blame] | 11 | class SelectBiasTest : TestBase() { |
Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 12 | val n = 10_000 |
| 13 | |
| 14 | @Test |
Vsevolod Tolstopyatov | 2cdbfd7 | 2018-04-22 18:26:14 +0300 | [diff] [blame] | 15 | fun testBiased() = runTest { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 16 | val d0 = async(coroutineContext) { 0 } |
| 17 | val d1 = async(coroutineContext) { 1 } |
Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 18 | val counter = IntArray(2) |
| 19 | repeat(n) { |
| 20 | val selected = select<Int> { |
| 21 | d0.onAwait { 0 } |
| 22 | d1.onAwait { 1 } |
| 23 | } |
| 24 | counter[selected]++ |
| 25 | } |
| 26 | assertEquals(n, counter[0]) |
| 27 | assertEquals(0, counter[1]) |
| 28 | } |
| 29 | |
| 30 | @Test |
Vsevolod Tolstopyatov | 2cdbfd7 | 2018-04-22 18:26:14 +0300 | [diff] [blame] | 31 | fun testUnbiased() = runTest { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 32 | val d0 = async(coroutineContext) { 0 } |
| 33 | val d1 = async(coroutineContext) { 1 } |
Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 34 | val counter = IntArray(2) |
| 35 | repeat(n) { |
| 36 | val selected = selectUnbiased<Int> { |
| 37 | d0.onAwait { 0 } |
| 38 | d1.onAwait { 1 } |
| 39 | } |
| 40 | counter[selected]++ |
| 41 | } |
| 42 | assertTrue(counter[0] >= n / 4) |
| 43 | assertTrue(counter[1] >= n / 4) |
| 44 | } |
| 45 | } |