Go program getting deadlock

后端 未结 1 2054
情话喂你
情话喂你 2021-01-16 12:33

Here is my Golang program which I am playing with just to get my concepts right. When I run the program it is deadlocked I don\'t understand why ? Please anyone point out wh

相关标签:
1条回答
  • 2021-01-16 13:02

    The problem is that you're passing a copy of sync.WaitGroup to the goroutines, rather than a reference (i.e. a pointer):

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    var wg sync.WaitGroup
    
    func main() {
    
        numOfGoRoutines := 10
        wg.Add(numOfGoRoutines)
        ch := make(chan int, numOfGoRoutines)
    
        for i := 0; i < numOfGoRoutines; i++ {
            a := i
            go sqr(ch, a, &wg)
        }
        wg.Wait()
        fmt.Println("After WAIT")
        close(ch)
        var res int
        for i := range ch {
            res += i
        }
        ch = nil
        fmt.Println("result = ", res)
    
    }
    
    func sqr(ch chan int, val int, wg *sync.WaitGroup) {
        fmt.Println("go - ", val)
        s := val * val
        ch <- s
        wg.Done()
    }
    

    Additionally, since wg is a global variable, you could just remove the parameter entirely:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    var wg sync.WaitGroup
    
    func main() {
    
        numOfGoRoutines := 10
        wg.Add(numOfGoRoutines)
        ch := make(chan int, numOfGoRoutines)
    
        for i := 0; i < numOfGoRoutines; i++ {
            a := i
            go sqr(ch, a)
        }
        wg.Wait()
        fmt.Println("After WAIT")
        close(ch)
        var res int
        for i := range ch {
            res += i
        }
        ch = nil
        fmt.Println("result = ", res)
    
    }
    
    func sqr(ch chan int, val int) {
        fmt.Println("go - ", val)
        s := val * val
        ch <- s
        wg.Done()
    }
    
    0 讨论(0)
提交回复
热议问题