Go 程序陷入僵局

这是我正在玩的 Golang 程序,只是为了让我的概念正确。当我运行程序时它死锁我不明白为什么?请任何人指出出了什么问题?


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()

}

输出是:


warning: GOPATH set to GOROOT (C:\\Go) has no effect

go -  9

go -  0

go -  1

go -  2

go -  3

go -  4

go -  5

go -  6

go -  7

go -  8

fatal error: all goroutines are asleep - deadlock!


goroutine 1 [semacquire]:

sync.runtime_Semacquire(0x5bcabc)

        C:/Go/src/runtime/sema.go:47 +0x2d

sync.(*WaitGroup).Wait(0x5bcab0)

        C:/Go/src/sync/waitgroup.go:127 +0xbb

main.main()

        C:/demo/go-work/main.go:20 +0xdf

exit status 2


缥缈止盈
浏览 178回答 1
1回答

慕丝7291255

问题是您将副本传递sync.WaitGroup给 goroutine,而不是引用(即指针):package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync")var wg sync.WaitGroupfunc main() {&nbsp; &nbsp; numOfGoRoutines := 10&nbsp; &nbsp; wg.Add(numOfGoRoutines)&nbsp; &nbsp; ch := make(chan int, numOfGoRoutines)&nbsp; &nbsp; for i := 0; i < numOfGoRoutines; i++ {&nbsp; &nbsp; &nbsp; &nbsp; a := i&nbsp; &nbsp; &nbsp; &nbsp; go sqr(ch, a, &wg)&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; fmt.Println("After WAIT")&nbsp; &nbsp; close(ch)&nbsp; &nbsp; var res int&nbsp; &nbsp; for i := range ch {&nbsp; &nbsp; &nbsp; &nbsp; res += i&nbsp; &nbsp; }&nbsp; &nbsp; ch = nil&nbsp; &nbsp; fmt.Println("result = ", res)}func sqr(ch chan int, val int, wg *sync.WaitGroup) {&nbsp; &nbsp; fmt.Println("go - ", val)&nbsp; &nbsp; s := val * val&nbsp; &nbsp; ch <- s&nbsp; &nbsp; wg.Done()}此外,由于wg是一个全局变量,您可以完全删除该参数:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync")var wg sync.WaitGroupfunc main() {&nbsp; &nbsp; numOfGoRoutines := 10&nbsp; &nbsp; wg.Add(numOfGoRoutines)&nbsp; &nbsp; ch := make(chan int, numOfGoRoutines)&nbsp; &nbsp; for i := 0; i < numOfGoRoutines; i++ {&nbsp; &nbsp; &nbsp; &nbsp; a := i&nbsp; &nbsp; &nbsp; &nbsp; go sqr(ch, a)&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; fmt.Println("After WAIT")&nbsp; &nbsp; close(ch)&nbsp; &nbsp; var res int&nbsp; &nbsp; for i := range ch {&nbsp; &nbsp; &nbsp; &nbsp; res += i&nbsp; &nbsp; }&nbsp; &nbsp; ch = nil&nbsp; &nbsp; fmt.Println("result = ", res)}func sqr(ch chan int, val int) {&nbsp; &nbsp; fmt.Println("go - ", val)&nbsp; &nbsp; s := val * val&nbsp; &nbsp; ch <- s&nbsp; &nbsp; wg.Done()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go