douyou2732 2017-10-12 07:29
浏览 17
已采纳

带通道的WaitGroup goroutines

I am learning WaitGroup from the blog https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/

the code:

package main

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

func main() {
    messages := make(chan int)
    var wg sync.WaitGroup

    // you can also add these one at 
    // a time if you need to 

    wg.Add(3)
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 3)
        messages <- 1
    }()
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 2)
        messages <- 2
    }() 
    go func() {
        defer wg.Done()
        time.Sleep(time.Second * 1)
        messages <- 3
    }()
    go func() {
        for i := range messages {
            fmt.Println(i)
        }
    }()

    wg.Wait()
}

I think it should print 3, 2 and 1 in order. But it only prints 3, 2 but 1 is missing, what's the problem?

You can tree it on https://play.golang.org/p/kZCvDhykYM

  • 写回答

3条回答 默认 最新

  • dsfdfdfd6576578 2017-10-12 07:32
    关注

    Right after the latest messages <- 1, the deferred wg.Done() is invoked which releases wg.Wait() in the end of the program and the program quits. When a program quits all the goroutines get killed, so the printing goroutine does not have a chance to print the latest value.

    If you put something like time.Sleep(time.Second * 1) right after wg.Done() you would be able to see all the output lines.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?