File tree Expand file tree Collapse file tree 2 files changed +25
-1
lines changed
kotlinx-coroutines-core/src
main/kotlin/kotlinx/coroutines/experimental/sync
test/kotlin/kotlinx/coroutines/experimental/sync Expand file tree Collapse file tree 2 files changed +25
-1
lines changed Original file line number Diff line number Diff line change @@ -92,10 +92,23 @@ public interface Mutex {
92
92
}
93
93
94
94
/* *
95
- * Executes the given [action] under this mutex.
95
+ * Executes the given [action] under this mutex's lock .
96
96
* @return the return value of the action.
97
97
*/
98
98
// :todo: this function needs to be make inline as soon as this bug is fixed: https://youtrack.jetbrains.com/issue/KT-16448
99
+ public suspend fun <T > Mutex.withLock (action : suspend () -> T ): T {
100
+ lock()
101
+ try {
102
+ return action()
103
+ } finally {
104
+ unlock()
105
+ }
106
+ }
107
+
108
+ /* *
109
+ * @suppress: **Deprecated**: Use [withLock]
110
+ */
111
+ @Deprecated(" Use `withLock`" , replaceWith = ReplaceWith (" withLock(action)" ))
99
112
public suspend fun <T > Mutex.withMutex (action : suspend () -> T ): T {
100
113
lock()
101
114
try {
Original file line number Diff line number Diff line change 16
16
17
17
package kotlinx.coroutines.experimental.sync
18
18
19
+ import guide.sync.example06.mutex
19
20
import kotlinx.coroutines.experimental.*
20
21
import org.junit.Assert.*
21
22
import org.junit.Test
@@ -61,6 +62,16 @@ class MutexTest : TestBase() {
61
62
assertFalse(mutex.isLocked)
62
63
}
63
64
65
+ @Test
66
+ fun withLockTest () = runBlocking {
67
+ val mutex = Mutex ()
68
+ assertFalse(mutex.isLocked)
69
+ mutex.withLock {
70
+ assertTrue(mutex.isLocked)
71
+ }
72
+ assertFalse(mutex.isLocked)
73
+ }
74
+
64
75
@Test
65
76
fun testStress () = runBlocking<Unit > {
66
77
val n = 1000 * stressTestMultiplier
You can’t perform that action at this time.
0 commit comments