dsnrixf6765 2015-08-11 14:59
浏览 31
已采纳

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

I looked at some code that I've wrote a long time ago, when go1.3 was released(I might be wrong). CODE HERE

The below code used to work as expected, but now since I've update go to the current master version(go version devel +bd1efd5 Fri Jul 31 16:11:21 2015 +0000 darwin/amd64), the last output message c <- "FUNC 1 DONE" is not printed, the code works as it should on play.golang.org. Did I do something wrong, or this is a bug?

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

UPDATE:

I'm not saying that, the above is the best way of doing those types of work, but I don't see anything wrong with it.

Also running it in go version go1.4.2 darwin/amd64 will return the expected output.

  • 写回答

1条回答 默认 最新

  • doulvli9462 2015-08-11 15:10
    关注

    Your code has always had this bug. It was only by chance that your program managed to print all messages before main exited.

    To make this work correctly, I would invert where you have the wg.Wait() and the channel receives, so you can asynchronously close the channel. This way the receive operations are what is blocking main, and the channel is closed as soon as all send operations are done.

    func main() {
        ch := make(chan string)
    
        var wg sync.WaitGroup
        wg.Add(2)
    
        go test(ch, &wg)
        go test1(ch, &wg)
    
        go func() {
            wg.Wait()
            close(ch)
        }()
    
        for txt := range ch {
            fmt.Println(txt)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作