Search code examples
gogoroutine

Listen one channel on multiple places in Go


I know if once get the data from a channel that data won't receive from any other place that channel is waiting. However, if I want to design a program broadcast that channel has got data and It is ready to take out in different places without affecting other channels but in all places, I need to receive data in the same order, what will be the best design?

As a example:

func sender(c chan int){
c-> 5
}

func reciever1(c chan int){
 i:= <-c
...
}

func reciever2(c chan int){
 i:= <-c
...
}

Here when executing both reciever1() and reciver2() Both should get same result.


Solution

  • You have to create multiple channels and pass the same value to each of those channels. Example

    package main
    import (
        "fmt"
    )
    
    func main(){
        chann1 := make(chan int)
        chann2 := make(chan int)
        go func(){
            for {
                val :=<- chann1
                fmt.Println("GORoutine 1", val)
            }
    
        }()
        go func(){
            for {
                val :=<- chann2
                fmt.Println("GORoutine 2", val)
            }
    
        }()
    
        for i:=0;i<=10;i++{
            chann1 <- i
            chann2 <- i
        }
    
    
    }