Fan-out and Fan-in

Several Workers, One Queue

Fan-out: many coroutines receive from the same channel, so work is shared between them. Fan-in: many coroutines send into one channel.

Fan-out:                       Fan-in:
            ┌─► worker 1           sensor A ─┐
jobs ───────┼─► worker 2           sensor B ─┼──► one channel ─► logger
            └─► worker 3           sensor C ─┘

Example

Example

Results are sorted before printing so the output does not depend on which worker was faster.

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*

fun main() = runBlocking {
    // fan-out
    val jobs = Channel<Int>()
    val done = Channel<String>(Channel.UNLIMITED)
    val workers = List(3) { w ->
        launch(Dispatchers.Default) {
            for (job in jobs) {
                delay(50)
                done.send("job $job done by a worker")
            }
        }
    }
    for (j in 1..6) jobs.send(j)
    jobs.close()
    workers.joinAll()
    done.close()
    done.toList().sorted().forEach(::println)

    // fan-in
    val readings = Channel<String>()
    listOf("temp" to 30, "humidity" to 65, "aqi" to 142).forEach { (name, value) ->
        launch { readings.send("$name=$value") }
    }
    val all = List(3) { readings.receive() }.sorted()
    println("Fan-in received: $all")
}

Output

job 1 done by a worker
job 2 done by a worker
job 3 done by a worker
job 4 done by a worker
job 5 done by a worker
job 6 done by a worker
Fan-in received: [aqi=142, humidity=65, temp=30]