Deor
11/09/2020, 6:23 PMThe current version of kotlinx.coroutines, which can be used for iOS, supports usage only in a single thread.
but supposedly there is a multithreded version
implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9-native-mt"){
version {
strictly("1.3.9-native-mt")
}
}
I can’t seem to make it work though and in the iOS app Everything is still done on a single background thread.Deor
11/09/2020, 6:24 PMsuspend fun testSingleTaskOnMultipleBackgroundThread() = withContext(coroutineDispatcher) {
val async1 = async(newSingleThreadContext("MyOwnThread")) { compute() }
val async2 = async(newSingleThreadContext("MyOwnThread_no2")) { compute() }
val async3 = async(newSingleThreadContext("MyOwnThread_no3")) { compute() }
val async4 = async(newSingleThreadContext("MyOwnThread_no4")) { compute() }
val async5 = async(newSingleThreadContext("MyOwnThread_no5")) { compute() }
val total = async1.await() + async2.await() + async3.await() + async4.await() + async5.await()
"four task on a background thread took $total adding them up"
}
fun testSingleTaskOnMultipleBackgroundThread(onComplete: (String) -> Unit) {
scope.launch {
val report = mutableListOf("Android parallel report:")
val duration = measureTime {
report.add(threadPerformance.testSingleTaskOnMultipleBackgroundThread())
}
report.add("four task on a background thread took $duration in parallel")
onComplete(report.joinToString(separator = "\n"))
}
}
Deor
11/09/2020, 6:25 PMlouiscad
11/10/2020, 8:26 AMDeor
11/10/2020, 9:01 AMDeor
11/10/2020, 9:01 AMlouiscad
11/10/2020, 11:07 AMDeor
11/10/2020, 2:20 PMDeor
11/10/2020, 2:20 PMsuspend fun testAsyncMultithreading() = withContext(dispatcherProvider.background) {
val async1 = async (dispatcherProvider.background) { compute() }
val async2 = async (dispatcherProvider.background) { compute() }
val async3 = async (dispatcherProvider.background) { compute() }
val async4 = async (dispatcherProvider.background) { compute() }
val async5 = async (dispatcherProvider.background) { compute() }
val total = async1.await() + async2.await() + async3.await() + async4.await() + async5.await()
println("four task on a background thread took $total adding them up")
}
Deor
11/10/2020, 2:21 PMactual class DispatcherProvider {
actual val main: CoroutineDispatcher = Dispatchers.Main
actual val background: CoroutineDispatcher
get() = newSingleThreadContext("BackgroundThread")
}
Deor
11/10/2020, 2:21 PMlouiscad
11/10/2020, 3:22 PMlouiscad
11/10/2020, 3:23 PMasync
that finally
closes the temporary dispatcher (or use the use
extension if it exists for this type)Deor
11/10/2020, 3:50 PMlouiscad
11/10/2020, 3:59 PM