Skip to content

Commit c02ee11

Browse files
committed
Renamed withMutex to withLock
1 parent f04f51d commit c02ee11

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

2 files changed

+25
-1
lines changed

kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/sync/Mutex.kt

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff 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)"))
99112
public suspend fun <T> Mutex.withMutex(action: suspend () -> T): T {
100113
lock()
101114
try {

kotlinx-coroutines-core/src/test/kotlin/kotlinx/coroutines/experimental/sync/MutexTest.kt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package kotlinx.coroutines.experimental.sync
1818

19+
import guide.sync.example06.mutex
1920
import kotlinx.coroutines.experimental.*
2021
import org.junit.Assert.*
2122
import 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

0 commit comments

Comments
 (0)