Skip to content

Commit 7650a50

Browse files
zhouxinelizarov
zhouxin
authored andcommitted
Mutex.withLock and Semaphore.withPermit EXACTLY_ONCE contract (#2010)
1 parent cfb5af4 commit 7650a50

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

kotlinx-coroutines-core/common/src/sync/Mutex.kt

+5
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import kotlinx.coroutines.*
99
import kotlinx.coroutines.internal.*
1010
import kotlinx.coroutines.intrinsics.*
1111
import kotlinx.coroutines.selects.*
12+
import kotlin.contracts.*
1213
import kotlin.coroutines.*
1314
import kotlin.jvm.*
1415
import kotlin.native.concurrent.*
@@ -106,7 +107,11 @@ public fun Mutex(locked: Boolean = false): Mutex =
106107
*
107108
* @return the return value of the action.
108109
*/
110+
@OptIn(ExperimentalContracts::class)
109111
public suspend inline fun <T> Mutex.withLock(owner: Any? = null, action: () -> T): T {
112+
contract {
113+
callsInPlace(action, InvocationKind.EXACTLY_ONCE)
114+
}
110115
lock(owner)
111116
try {
112117
return action()

kotlinx-coroutines-core/common/src/sync/Semaphore.kt

+5
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package kotlinx.coroutines.sync
77
import kotlinx.atomicfu.*
88
import kotlinx.coroutines.*
99
import kotlinx.coroutines.internal.*
10+
import kotlin.contracts.*
1011
import kotlin.coroutines.*
1112
import kotlin.math.*
1213
import kotlin.native.concurrent.SharedImmutable
@@ -74,7 +75,11 @@ public fun Semaphore(permits: Int, acquiredPermits: Int = 0): Semaphore = Semaph
7475
*
7576
* @return the return value of the [action].
7677
*/
78+
@OptIn(ExperimentalContracts::class)
7779
public suspend inline fun <T> Semaphore.withPermit(action: () -> T): T {
80+
contract {
81+
callsInPlace(action, InvocationKind.EXACTLY_ONCE)
82+
}
7883
acquire()
7984
try {
8085
return action()

0 commit comments

Comments
 (0)