Last active
October 21, 2023 17:29
-
-
Save orcchg/d126ec561eb0e3ae0a6ae252a6936a41 to your computer and use it in GitHub Desktop.
Critical section for coroutines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.ConcurrentHashMap | |
import kotlin.coroutines.Continuation | |
import kotlin.coroutines.resume | |
import kotlin.coroutines.suspendCoroutine | |
class KCriticalSection { | |
private val suspendedJobs = ConcurrentHashMap<Int, Continuation<Boolean>>() | |
private var id = AtomicInteger(1000) | |
@Volatile private var isInsideCriticalSection = false | |
suspend fun <T> synchronized(block: suspend () -> T): T { | |
val thisJobId = id.getAndIncrement() | |
while (isInsideCriticalSection) { | |
suspendCoroutine { cont -> // <-- suspending call | |
suspendedJobs[thisJobId] = cont | |
} | |
suspendedJobs.remove(thisJobId) | |
} | |
isInsideCriticalSection = true | |
val result = block() // <-- suspending call | |
isInsideCriticalSection = false | |
suspendedJobs.forEach { (id, cont) -> | |
cont.resume(true) | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment