blob: f2204dcb92a35874c24b569116c52eee82ab50fc [file] [log] [blame]
Roman Elizarov174c6962017-02-28 17:36:51 +03001/*
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
17package kotlinx.coroutines.experimental.selects
18
Roman Elizarov9fe5f462018-02-21 19:05:52 +030019import kotlinx.coroutines.experimental.*
20import kotlinx.coroutines.experimental.sync.*
Roman Elizarov9fe5f462018-02-21 19:05:52 +030021import kotlin.coroutines.experimental.*
Roman Elizarovaa461cf2018-04-11 13:20:29 +030022import kotlin.test.*
Roman Elizarov174c6962017-02-28 17:36:51 +030023
24class SelectMutexTest : TestBase() {
25 @Test
Roman Elizarov8b38fa22017-09-27 17:44:31 +030026 fun testSelectLock() = runTest {
Roman Elizarov174c6962017-02-28 17:36:51 +030027 val mutex = Mutex()
28 expect(1)
Roman Elizarov43e3af72017-07-21 16:01:31 +030029 launch(coroutineContext) { // ensure that it is not scheduled earlier than needed
Roman Elizarov8b38fa22017-09-27 17:44:31 +030030 finish(4) // after main exits
Roman Elizarov174c6962017-02-28 17:36:51 +030031 }
32 val res = select<String> {
33 mutex.onLock {
34 assertTrue(mutex.isLocked)
35 expect(2)
36 "OK"
37 }
38 }
39 assertEquals("OK", res)
Roman Elizarov8b38fa22017-09-27 17:44:31 +030040 expect(3)
41 // will wait for the first coroutine
Roman Elizarov174c6962017-02-28 17:36:51 +030042 }
43
44 @Test
Roman Elizarov8b38fa22017-09-27 17:44:31 +030045 fun testSelectLockWait() = runTest {
Roman Elizarov174c6962017-02-28 17:36:51 +030046 val mutex = Mutex(true) // locked
47 expect(1)
Roman Elizarov43e3af72017-07-21 16:01:31 +030048 launch(coroutineContext) {
Roman Elizarov174c6962017-02-28 17:36:51 +030049 expect(3)
Roman Elizarovaa461cf2018-04-11 13:20:29 +030050 val res = select<String> {
51 // will suspended
Roman Elizarov174c6962017-02-28 17:36:51 +030052 mutex.onLock {
53 assertTrue(mutex.isLocked)
54 expect(6)
55 "OK"
56 }
57 }
58 assertEquals("OK", res)
59 expect(7)
60 }
61 expect(2)
62 yield() // to launched coroutine
63 expect(4)
64 mutex.unlock()
65 expect(5)
66 yield() // to resumed select
67 finish(8)
68 }
Roman Elizarov174c6962017-02-28 17:36:51 +030069}