blob: 7b019ff5adbd0ebf6df61c19d55b8592bf9de4cd [file] [log] [blame]
Roman Elizarov174c6962017-02-28 17:36:51 +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 Elizarov174c6962017-02-28 17:36:51 +03003 */
4
5package kotlinx.coroutines.experimental.selects
6
Roman Elizarov9fe5f462018-02-21 19:05:52 +03007import kotlinx.coroutines.experimental.*
8import kotlinx.coroutines.experimental.sync.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +03009import kotlin.coroutines.experimental.*
Roman Elizarovaa461cf2018-04-11 13:20:29 +030010import kotlin.test.*
Roman Elizarov174c6962017-02-28 17:36:51 +030011
12class SelectMutexTest : TestBase() {
13 @Test
Roman Elizarov8b38fa22017-09-27 17:44:31 +030014 fun testSelectLock() = runTest {
Roman Elizarov174c6962017-02-28 17:36:51 +030015 val mutex = Mutex()
16 expect(1)
Roman Elizarov43e3af72017-07-21 16:01:31 +030017 launch(coroutineContext) { // ensure that it is not scheduled earlier than needed
Roman Elizarov8b38fa22017-09-27 17:44:31 +030018 finish(4) // after main exits
Roman Elizarov174c6962017-02-28 17:36:51 +030019 }
20 val res = select<String> {
21 mutex.onLock {
22 assertTrue(mutex.isLocked)
23 expect(2)
24 "OK"
25 }
26 }
27 assertEquals("OK", res)
Roman Elizarov8b38fa22017-09-27 17:44:31 +030028 expect(3)
29 // will wait for the first coroutine
Roman Elizarov174c6962017-02-28 17:36:51 +030030 }
31
32 @Test
Roman Elizarov8b38fa22017-09-27 17:44:31 +030033 fun testSelectLockWait() = runTest {
Roman Elizarov174c6962017-02-28 17:36:51 +030034 val mutex = Mutex(true) // locked
35 expect(1)
Roman Elizarov43e3af72017-07-21 16:01:31 +030036 launch(coroutineContext) {
Roman Elizarov174c6962017-02-28 17:36:51 +030037 expect(3)
Roman Elizarovaa461cf2018-04-11 13:20:29 +030038 val res = select<String> {
39 // will suspended
Roman Elizarov174c6962017-02-28 17:36:51 +030040 mutex.onLock {
41 assertTrue(mutex.isLocked)
42 expect(6)
43 "OK"
44 }
45 }
46 assertEquals("OK", res)
47 expect(7)
48 }
49 expect(2)
50 yield() // to launched coroutine
51 expect(4)
52 mutex.unlock()
53 expect(5)
54 yield() // to resumed select
55 finish(8)
56 }
Roman Elizarov174c6962017-02-28 17:36:51 +030057}