猿问

golang chanel 无法与 sync.WaitGroup 一起使用

我的代码




package main


import (

   "fmt"

   "sync"

)


func other(c chan int, wg *sync.WaitGroup) {

   c <- 455

   wg.Done()

}


func addInt(c chan int, d int, wg *sync.WaitGroup) {

   c <- d

   wg.Done()

}

func main() {


   var wg sync.WaitGroup

   myChanel := make(chan int)


   wg.Add(2)


   go addInt(myChanel, 5, &wg)

   go other(myChanel, &wg)


   wg.Wait()


   c := 0



   for v := range myChanel {

       if c == 1 {


           close(myChanel)

       }

       fmt.Println(v)

       c++


   }


}



我正在学习 golang 看地雷,但我确实遇到了这样的错误。我查看了其他来源。我无法找到健康的解决方案。我再次尝试关闭(香奈儿)。


错误输出


fatal error: all goroutines are asleep - deadlock!


goroutine 1 [semacquire]:

sync.runtime_Semacquire(0xc0000140f8)

        /usr/lib/go-1.13/src/runtime/sema.go:56 +0x42

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

        /usr/lib/go-1.13/src/sync/waitgroup.go:130 +0x64

main.main()

        /home/zeus/go/src/github.com/awesomeProject/pool.go:27 +0xe4


goroutine 6 [chan send]:

main.addInt(0xc000016120, 0x5, 0xc0000140f0)

        /home/zeus/go/src/github.com/awesomeProject/pool.go:14 +0x3f

created by main.main

        /home/zeus/go/src/github.com/awesomeProject/pool.go:24 +0xaa


goroutine 7 [chan send]:

main.other(0xc000016120, 0xc0000140f0)

        /home/zeus/go/src/github.com/awesomeProject/pool.go:9 +0x37

created by main.main

        /home/zeus/go/src/github.com/awesomeProject/pool.go:25 +0xd6

exit status 2


肥皂起泡泡
浏览 168回答 2
2回答

慕慕森

你有一个无缓冲的通道,这意味着你不能在它上面发送,直到有东西等待接收。所以当你这样做时:wg.Wait()在你做之前for&nbsp;v&nbsp;:=&nbsp;range&nbsp;myChanel您将永远无法到达接收器。无论如何,在使用无缓冲通道时,我从来不需要使用等待组,根据我的经验,您只需要在没有通道的情况下进行并发处理时才需要它们。你可以这样做:https:&nbsp;//play.golang.org/p/-SUuXGlFd1E

12345678_0001

我解决了运行package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time")func other(c chan int, wg *sync.WaitGroup) {&nbsp; &nbsp; time.Sleep(time.Second*1)&nbsp; &nbsp; c <- 455&nbsp; &nbsp; wg.Done()}func addInt(c chan int, d int, wg *sync.WaitGroup) {&nbsp; &nbsp; c <- d&nbsp; &nbsp; wg.Done()}func main() {&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; myChanel := make(chan int)&nbsp; &nbsp; wg.Add(2)&nbsp; &nbsp; go addInt(myChanel, 5, &wg)&nbsp; &nbsp; go other(myChanel, &wg)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; &nbsp; &nbsp; close(myChanel)&nbsp; &nbsp; }()&nbsp; &nbsp; for v := range myChanel {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(v)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答