blob: cd7f651c9a9030687e41988311730cd62b2e3af1 [file] [log] [blame]
Roman Elizarov04d11ca2017-02-27 12:47:32 +03001/*
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03002 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarov04d11ca2017-02-27 12:47:32 +03003 */
4
5package kotlinx.coroutines.experimental.selects
6
Roman Elizarov9fe5f462018-02-21 19:05:52 +03007import kotlinx.coroutines.experimental.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +03008import kotlin.coroutines.experimental.*
Vsevolod Tolstopyatov2cdbfd72018-04-22 18:26:14 +03009import kotlin.test.*
Roman Elizarov04d11ca2017-02-27 12:47:32 +030010
Vsevolod Tolstopyatov2cdbfd72018-04-22 18:26:14 +030011class SelectBiasTest : TestBase() {
Roman Elizarov04d11ca2017-02-27 12:47:32 +030012 val n = 10_000
13
14 @Test
Vsevolod Tolstopyatov2cdbfd72018-04-22 18:26:14 +030015 fun testBiased() = runTest {
Roman Elizarov43e3af72017-07-21 16:01:31 +030016 val d0 = async(coroutineContext) { 0 }
17 val d1 = async(coroutineContext) { 1 }
Roman Elizarov04d11ca2017-02-27 12:47:32 +030018 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 Tolstopyatov2cdbfd72018-04-22 18:26:14 +030031 fun testUnbiased() = runTest {
Roman Elizarov43e3af72017-07-21 16:01:31 +030032 val d0 = async(coroutineContext) { 0 }
33 val d1 = async(coroutineContext) { 1 }
Roman Elizarov04d11ca2017-02-27 12:47:32 +030034 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}