简体   繁体   中英

Kotlin Concurrency: Any standard function to run code in a Lock?

I've been searching for a function that takes an object of type Lock and runs a block of code with that lock taking care of locking and also unlocking.

I'd implement it as follows:

fun <T : Lock> T.runLocked(block: () -> Unit) {
    lock()
    try {
        block()
    } finally {
        unlock()
    }
}

Used like this:

val l = ReentrantLock()
l.runLocked {
    println(l.isLocked)
}

println(l.isLocked)
//true
//false

Anything available like this? I could only find the synchronized function which cannot be used like this.

You are looking for withLock , which has the exact implementation you've written yourself, except it has a generic parameter for the result of the block instead of the receiver type.

You can find other concurrency related methods of the standard library here , in the kotlin.concurrent package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM