【发布时间】:2020-06-16 10:34:17
【问题描述】:
我想从协程中同步访问代表我的状态的变量。我该如何解决这个问题?
private var myState: MyState? = null
get() = mutex.withLock {
return@withLock myState
}
set(value) = mutex.withLock {
field = value
}
private val mutex = Mutex()
现在我收到Suspend function 'withLock' should be called only from a coroutine or another suspend function 消息。
如果不可能有任何替代的优雅解决方案?
【问题讨论】:
-
Writes to and reads of references are always atomic, regardless of whether they are implemented as 32-bit or 64-bit values.docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.7,这里不需要互斥体
标签: kotlin getter-setter kotlin-coroutines