https://kotlinlang.org logo
#coroutines
Title
# coroutines
n

nulldev

11/03/2018, 9:20 PM
Nevermind, actually solved this in a very nice way using
select
on
send
. I just allocated an output and input channel for each worker:
Copy code
suspend fun invoke(input: InputType): OutputType {
        return selectUnbiased {
            for(worker in runningWorkers) {
                worker.inputChannel.onSend(input) {
                    worker.outputChannel.receive()
                }
            }
        }
    }
z

Zach Klippenstein (he/him) [MOD]

11/04/2018, 6:29 PM
If input value and output value are matched 1:1, include the output in the input, so you don’t have to worry about races. E.g.:
Copy code
data class WorkerTask(val input: InputType) {
  val output = CompletableDeferred<OutputType>
}

class WorkerPool {
  val chanToWorkers = Channel<WorkerTask>()

  suspend fun doStuff(input: InputType): OutputType {
    val task = WorkerTask(input)
    chanToWorkers.send(task)
    return task.output.await()
  }
}
3 Views