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 {
9292}
9393
9494/* *
95- * Executes the given [action] under this mutex.
95+ * Executes the given [action] under this mutex's lock .
9696 * @return the return value of the action.
9797 */
9898// :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)" ))
99112public suspend fun <T > Mutex.withMutex (action : suspend () -> T ): T {
100113 lock()
101114 try {
Original file line number Diff line number Diff line change 1616
1717package kotlinx.coroutines.experimental.sync
1818
19+ import guide.sync.example06.mutex
1920import kotlinx.coroutines.experimental.*
2021import org.junit.Assert.*
2122import org.junit.Test
@@ -61,6 +62,16 @@ class MutexTest : TestBase() {
6162 assertFalse(mutex.isLocked)
6263 }
6364
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+
6475 @Test
6576 fun testStress () = runBlocking<Unit > {
6677 val n = 1000 * stressTestMultiplier
You can’t perform that action at this time.
0 commit comments