Search code examples
gogoroutine

Loop values for one go channel to other


Could anyone please review my code and can check why I am facing a deadlock?

package main

import (
    "fmt"
    "sync"
)

func main() {

    myCh := make(chan int, 10)
    wg := &sync.WaitGroup{}

    wg.Add(10)

    // READ ONLY
    go func(ch <-chan int, wg *sync.WaitGroup) {
        value := <-myCh
        fmt.Println(value)
        wg.Done()
    }(myCh, wg)

    // send ONLY
    go func(ch chan<- int, wg *sync.WaitGroup) {
        for i := 0; i < 10; i++ {
            myCh <- i
        }
        wg.Done()
    }(myCh, wg)

    wg.Wait()
}

I want to send the loop values from SEND CHANNEL and OTHER CHANNEL should only recieve the values of each iteration.


Solution

  • Your reader go routine exits after the FIRST received data. You have to include a for loop into it to continously read that channel.

    Secondly you don't need to call wg.Sync() in your outer loop, because it also decreases the waitgroup.

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func main() {
        myCh := make(chan int, 10)
        wg := &sync.WaitGroup{}
        
        wg.Add(10)
        
        // READ ONLY
        go func(ch <-chan int, wg *sync.WaitGroup) {
            for value := range myCh { // this loop will read the channel continously
                fmt.Println(value)
                wg.Done()
            }
        }(myCh, wg)
        
        // send ONLY
        go func(ch chan<- int, wg *sync.WaitGroup) {
            for i := 0; i < 10; i++ {
                myCh <- i
            }
            //      wg.Done() <- This not needed here
        }(myCh, wg)
        
        wg.Wait()
        fmt.Println("DONE")
    }