forked from Kotlin/kotlinx.coroutines
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPermitTransfer.kt
45 lines (38 loc) · 1.19 KB
/
PermitTransfer.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package kotlinx.coroutines.internal
import kotlinx.atomicfu.*
internal class PermitTransferStatus {
private val status = atomic(false)
fun check(): Boolean = status.value
fun complete(): Boolean = status.compareAndSet(false, true)
}
internal expect class PermitTransfer constructor() {
/**
* [releasePermit] may throw
*/
fun releaseFun(releasePermit: () -> Unit): () -> Unit
/**
* [tryAllocatePermit] and [deallocatePermit] must not throw
*/
fun acquire(tryAllocatePermit: () -> Boolean, deallocatePermit: () -> Unit)
}
internal class BusyPermitTransfer {
private val status = PermitTransferStatus()
fun releaseFun(releasePermit: () -> Unit): () -> Unit = {
if (status.complete()) {
releasePermit()
}
}
fun acquire(tryAllocatePermit: () -> Boolean, deallocatePermit: () -> Unit) {
while (true) {
if (status.check()) {
return
}
if (tryAllocatePermit()) {
if (!status.complete()) { // race: transfer was completed first by releaseFun
deallocatePermit()
}
return
}
}
}
}