Android Kotlin 同步和 FileInputStream.read 导致线程饥饿警告

问题描述 投票:0回答:1

我想通过使用“同步”来防止读取和写入同时发生。但是,这会导致警告:在非阻塞上下文中可能阻塞调用可能会导致线程饥饿

fun read(inputStream: FileInputStream) {
    synchronized(this) {
        // warning: Possibly blocking call in non-blocking context could lead to thread starvation
        var nextByte: Int = inputStream.read()    
    }
}

fun write(outputStream: FileOutputStream, data: ByteArray) {
    synchronized(this) {
        outputStream.write(data)
    }
}

我目前无法将这段代码重写为协程。还有其他方法可以解决这个问题吗?

编辑:想要添加这是否对任何人都有帮助,使用锁而不是同步对我的用例很有用。不确定其他人的情况。

android kotlin file synchronization
1个回答
0
投票

如果这对其他人有帮助,我从synchronize()更改为可重入锁。有几种使用可重入锁的方法,但有一个函数与synchronized()的块结构非常相似。

lock.withLock {
  // your code here
}

而不是

synchronized(object) {
  // your code here
}
© www.soinside.com 2019 - 2024. All rights reserved.