Fan Out Fan In

Fan-out

  • Multiple goroutines are started to read data from the single channel.
  • Dirstribute work amongst a group of workers goroutines to parallelize the CPU usage adn I/O usage.
  • Helps computational intensive stage to run faster.

Fan-in

  • Process of combining multiple results into one channel
  • We crate Merge goroutines, to read data from multiple input channels adn send the data a single output channel.

Image

Exercises

https://go.dev/play/p/ZymG0qZT3nu

// generator() -> square() -> print

package main

import (
    "fmt"
    "sync"
)

func generator(nums ...int) <-chan int {
    out := make(chan int)

    go func() {
        for _, n := range nums {
            out <- n
        }
        close(out)
    }()
    return out
}

func square(in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        for n := range in {
            out <- n * n
        }
        close(out)
    }()
    return out
}

func merge(cs ...<-chan int) <-chan int {
    // Implement fan-in
    out := make(chan int)
    var wg sync.WaitGroup

    // merge a list of channels to a single channel
    output := func(c <-chan int) {
        defer wg.Done()
        for n := range c {
            out <- n
        }
    }

    wg.Add(len(cs))
    for _, c := range cs {
        go output(c)
    }
    go func() {
        wg.Wait()
        close(out)
    }()

    return out
}

func main() {
    in := generator(2, 3)

    // fan out square stage to run two instances.
    c1 := square(in)
    c2 := square(in)

    //  fan in the results of square stages.
    for n := range merge(c1, c2) {
        fmt.Println(n)
    }

}
© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:04:54

results matching ""

    No results matching ""

    results matching ""

      No results matching ""