GoRoutines,带有 WaitGroup 意外输出的通道

我看了一些我很久以前写的代码,当时 go1.3 发布(我可能错了)。代码在这里


下面的代码曾经按预期工作,但现在因为我已经更新go到当前的主版本(go version devel +bd1efd5 Fri Jul 31 16:11:21 2015 +0000 darwin/amd64),最后的输出消息c <- "FUNC 1 DONE"没有打印,代码正常工作play.golang.org。我做错了什么,还是这是一个错误?


package main


import ("fmt";"sync";"time")


func test(c chan string, wg *sync.WaitGroup) {

  defer wg.Done()

  fmt.Println("EXEC FUNC 1")

  time.Sleep(3 * time.Second)

  c <- "FUNC 1 DONE"

}


func test1(c chan string, wg *sync.WaitGroup) {

  defer wg.Done()

  fmt.Println("EXEC FUNC 2")

  time.Sleep(2 * time.Second)

  c <- "FUNC 2 DONE"

}


func main() {

  ch := make(chan string)


  var wg sync.WaitGroup

  wg.Add(2)


  go test(ch, &wg)

  go test1(ch, &wg)


  go func(c chan string) {

    for txt := range c {

      fmt.Println(txt)

    }

  }(ch)


  wg.Wait()

}

更新:


我不是说,以上是完成这些类型工作的最佳方式,但我认为它没有任何问题。


同时运行它go version go1.4.2 darwin/amd64会返回预期的输出。


人到中年有点甜
浏览 171回答 1
1回答

Helenr

你的代码一直有这个错误。您的程序在 main 退出之前设法打印了所有消息,这只是偶然的。为了使其正常工作,我会反转您拥有wg.Wait()和通道接收的位置,以便您可以异步关闭通道。这种方式接收操作是阻塞的main,一旦所有发送操作完成,通道就会关闭。func main() {&nbsp; &nbsp; ch := make(chan string)&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; wg.Add(2)&nbsp; &nbsp; go test(ch, &wg)&nbsp; &nbsp; go test1(ch, &wg)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; &nbsp; &nbsp; close(ch)&nbsp; &nbsp; }()&nbsp; &nbsp; for txt := range ch {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(txt)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go