Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2016-2017 JetBrains s.r.o. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package kotlinx.coroutines.experimental.selects |
| 18 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 19 | import kotlinx.coroutines.experimental.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 20 | import kotlin.coroutines.experimental.* |
Vsevolod Tolstopyatov | 2cdbfd7 | 2018-04-22 18:26:14 +0300 | [diff] [blame] | 21 | import kotlin.test.* |
Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 22 | |
Vsevolod Tolstopyatov | 2cdbfd7 | 2018-04-22 18:26:14 +0300 | [diff] [blame] | 23 | class SelectBiasTest : TestBase() { |
Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 24 | val n = 10_000 |
| 25 | |
| 26 | @Test |
Vsevolod Tolstopyatov | 2cdbfd7 | 2018-04-22 18:26:14 +0300 | [diff] [blame] | 27 | fun testBiased() = runTest { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 28 | val d0 = async(coroutineContext) { 0 } |
| 29 | val d1 = async(coroutineContext) { 1 } |
Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 30 | val counter = IntArray(2) |
| 31 | repeat(n) { |
| 32 | val selected = select<Int> { |
| 33 | d0.onAwait { 0 } |
| 34 | d1.onAwait { 1 } |
| 35 | } |
| 36 | counter[selected]++ |
| 37 | } |
| 38 | assertEquals(n, counter[0]) |
| 39 | assertEquals(0, counter[1]) |
| 40 | } |
| 41 | |
| 42 | @Test |
Vsevolod Tolstopyatov | 2cdbfd7 | 2018-04-22 18:26:14 +0300 | [diff] [blame] | 43 | fun testUnbiased() = runTest { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 44 | val d0 = async(coroutineContext) { 0 } |
| 45 | val d1 = async(coroutineContext) { 1 } |
Roman Elizarov | 04d11ca | 2017-02-27 12:47:32 +0300 | [diff] [blame] | 46 | val counter = IntArray(2) |
| 47 | repeat(n) { |
| 48 | val selected = selectUnbiased<Int> { |
| 49 | d0.onAwait { 0 } |
| 50 | d1.onAwait { 1 } |
| 51 | } |
| 52 | counter[selected]++ |
| 53 | } |
| 54 | assertTrue(counter[0] >= n / 4) |
| 55 | assertTrue(counter[1] >= n / 4) |
| 56 | } |
| 57 | } |