Reputation: 33
I've been trying to run tasks in a Kotlin-Multiplatform lib on a background thread on the iOS project and ran into some problems:
I tried using both Kotlin-Coroutines and the platform libs for GCD and have only been able to run tasks in the the main thread in iOS. Whenever I try sending something asynchronously to a background thread, the iOS app crashes with the following error:
"kotlin.native.IncorrectDereferenceException: illegal attempt to access non-shared com.hp.jarvis.kmm.LogFile.$saveLog$lambda-0$FUNCTION_REFERENCE$9@155a948 from other thread"
Upvotes: 3
Views: 2076
Reputation: 7700
IncorrectDereferenceException
is basically a signal that you're trying to access a global state from a background thread.
You could play around with:
@ThreadLocal
-> Makes a copy for every thread of a specific object@SharedImmutable
-> Will froze your object and make it available for all threads, note that if you'll try to change the value of a frozen object you'll get InvalidMutabilityException
I'd definitely give a read for this blog to understand the current memory model: https://touchlab.co/kotlin-native-concurrency/
Upvotes: 4