简体   繁体   English

Kotlin 并发:任何在锁中运行代码的标准函数?

[英]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.我一直在寻找一个函数,它接受一个Lock类型的对象并运行一个带有该锁的代码块,负责锁定和解锁。

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.我只能找到无法像这样使用的synchronized功能。

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.您正在寻找withLock ,它具有您自己编写的确切实现,但它具有用于块结果的通用参数而不是接收器类型。

You can find other concurrency related methods of the standard library here , in the kotlin.concurrent package.你可以找到标准库的其他并发相关的方法在这里,在kotlin.concurrent包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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