Home > Software design >  Loop values for one go channel to other
Loop values for one go channel to other

Time:02-05

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.

CodePudding user response:

You are adding delta = 10 in wg.Add(10), and call wg.Done() only twice.

You should either call wg.Add(2) or call wg.Done() ten times.

Right now the main function locks at wg.Wait() and waits for eight more wg.Done() calls.

CodePudding user response:

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")
}
  •  Tags:  
  • Related