Laurent Laborde
09/14/2022, 5:08 PMLaurent Laborde
09/14/2022, 5:12 PMCasey Brooks
09/14/2022, 5:20 PMLaurent Laborde
09/14/2022, 5:39 PMOliver.O
09/14/2022, 5:53 PMCasey Brooks
09/14/2022, 5:55 PMDispatchers.Main
for single-threaded UI code (platform-dependant), Dispatchers.Default
for general CPU-bound parallel work (I believe it’s limited to at most N+1 threads, where N is the number of CPU cores), <http://Dispatchers.IO|Dispatchers.IO>
for IO-based work (basically an unlimited number of threads).
For example:
suspend fun massivelyParallel() {
withContext(Dispatchers.Default) {
// anything launched in here will be launched onto the Default thread pool
// launch 10 jobs to all run in parallel. Replace `async` with `launch` for a fire-and-forget model
val tasksRunningInThreadPool = (1..10).map {
async {
delay(5000)
}
}
// wait for all 10 jobs to complete before continuing
tasksRunningInThreadPool.awaitAll()
}
}
Casey Brooks
09/14/2022, 5:58 PMDispatchers.Default
still runs your code concurrently so it still behaves similar to multithreaded code, even though it’s technically single-threadedLaurent Laborde
09/14/2022, 6:05 PMCasey Brooks
09/14/2022, 6:09 PMCasey Brooks
09/14/2022, 6:12 PMlaunch { }
per creature” and you let the coroutines framework figure out the rest. It typically ends up being more efficient than threads overall with fewer wasted system resources, and you don’t really notice the difference unless you’re storing data in ThreadLocal
variablesLaurent Laborde
09/14/2022, 6:16 PMLaurent Laborde
09/14/2022, 6:17 PMLaurent Laborde
09/14/2022, 6:28 PMMarcus Brito
09/15/2022, 1:19 PMLaurent Laborde
09/15/2022, 3:46 PM