Skip to content

Commit e470df9

Browse files
ZhouGongZaiShizhouxin
and
zhouxin
authored
Mutex.withLock() and Semaphore.withPermit() with EXACTLY_ONCE contract (#2010)
Co-authored-by: zhouxin <[email protected]>
1 parent 4511c23 commit e470df9

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

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

+6
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,12 @@ 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+
}
115+
110116
lock(owner)
111117
try {
112118
return action()

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

+6
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,12 @@ 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+
}
83+
7884
acquire()
7985
try {
8086
return action()

0 commit comments

Comments
 (0)