When I was learning the KN concurrency model, I di...
# kotlin-native
l
When I was learning the KN concurrency model, I did some concurrency experiments and some strange problems appeared,here is the code:
Copy code
// Uncaught Kotlin exception: kotlin.IllegalStateException: Illegal transfer state
fun test(): Test {
    return Worker.start().execute(TransferMode.SAFE, { atomic(Test()) }) {
        it.value.a += 100
        it
    }.result.value
}
// fine
fun test1(): Test {
    return Worker.start().execute(TransferMode.SAFE, { Test() }) {
        it.a += 100
        it
    }.result
}
k
Transferring state is difficult and can lead to confusing issues. I would not generally recommend you do that unless necessary. However, please post the actual stack trace.
This post won’t help much figuring out your issue, but thoughts on state transfer: https://dev.to/touchlab/kotlin-native-transferring-state-4n8i
I assume if you froze the atomic it would be fine. Also, there are cases where you need to explicitly run the gc before trying to transfer state
l
Actually, its not what i want. i just do some test to help me understand the model. Recently, i try to rewrite my android library into MPP. it almost done except the part of concurrency. i want to do some jobs in background thread, and when it finish, notify the main thread. But a mutable object reference can not be shared by two thread, so the Channel is not work. And the
future.result
will block the main thread which i dont want. I don't know what to do anymore😰
k
This is basically all I talk about now.
When you say “Channel” I assume you mean coroutines. Currently coroutines for native are single threaded, although that should be changing soon. There are a number of other concurrency options. Please check out https://github.com/touchlab/KaMPKit
You will need to learn some new stuff, but it’s not all that bad
k
Nice explanation @kpgalligan
a
@Luoqiaoyou do you really need to share a mutable object between threads? Would not it be enough for you to do some job in background then pass its result to the main thread and update a mutable object with the result (or update UI)?
l
@Arkadii Ivanov its not necessary. But how can the main thread immediately get a notification when background thread finish the Job. “Coroutine” not support multi thread in KN. “Channel” can not hold by two thread, otherwise “Worker” will throw a error. “Future.result” will block main thread. That’s all I know so far.
a
With coroutines it is currently not possible. But you can use other things 🙂
l
Copy code
coroutines:1.3.5-native-mt-1.3.71-release-429
I use this version. It's not stable but it can support multi thread in Kotlin 1.3.7
k
Don't worry soon it will stable, development is fast.