简体   繁体   中英

Get return value from thread, is this Kotlin code thread safe?

I would like to run some treads, wait till all of them are finished and get the results.

Possible way to do that would be in the code below. Is it thread safe though?

import kotlin.concurrent.thread

sealed class Errorneous<R>
data class Success<R>(val result: R) : Errorneous<R>()
data class Fail<R>(val error: Exception) : Errorneous<R>()

fun <R> thread_with_result(fn: () -> R): (() -> Errorneous<R>) {
  var r: Errorneous<R>? = null
  val t = thread {
    r = try { Success(fn()) } catch (e: Exception) { Fail(e) }
  }
  return {
    t.join()
    r!!
  }
}

fun main() {
  val tasks = listOf({ 2 * 2 }, { 3 * 3 })
  val results = tasks
    .map{ thread_with_result(it) }
    .map{ it() }
  println(results)
}

PS

Are there better built-in tools in Kotlin to do that? Like process 10000 tasks with pool of 10 threads?

It should be threads, not coroutines, as it will be used with legacy code and I don't know if it works well with coroutines.

Seems like Java has Executors that doing exactly that

fun <R> execute_in_parallel(tasks: List<() -> R>, threads: Int): List<Errorneous<R>> {
  val executor = Executors.newFixedThreadPool(threads)
  val fresults = executor.invokeAll(tasks.map { task ->
    Callable<Errorneous<R>> {
      try { Success(task()) } catch (e: Exception) { Fail(e) }
    }
  })
  return fresults.map { future -> future.get() }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM