为什么该go程序在完成打印后仍会打印?

时间:2018-07-28 20:15:19

标签: go producer-consumer

我实现了生产者-消费者模式,但是我看到了一个奇怪的行为。
多次运行不会一次定期发生这种情况。

package main

import (
    "fmt"
    "sync"
)

func main() {
    works := make(chan string)
    var wg sync.WaitGroup
    wg.Add(2)
    go func() {
        defer wg.Done()
        generators(2, works)
    }()
    go func() {
        defer wg.Done()
        readers(3, works)
    }()
    wg.Wait()
    fmt.Println("Done!")
}

func generators(numberOfProducers int, works chan string) {
    var wg sync.WaitGroup
    for i := 0; i < numberOfProducers; i++ {
        name := fmt.Sprintf("gen#%d", i)
        wg.Add(1)
        go func() {
            defer wg.Done()
            for i := 0; i < 5; i++ {
                works <- fmt.Sprintf("%s-%d", name, i)
            }
        }()
    }
    wg.Wait()
    close(works)
}

func readers(numberOfConsumers int, works chan string) {
    for i := 0; i < numberOfConsumers; i++ {
        name := fmt.Sprintf("reader #%d", i)
        go func() {
            for task := range works {
                fmt.Println(name, " got ", task)
            }
        }()
    }
}

我希望“完成!”是屏幕上最后打印的东西,像这样:

reader #2  got  gen#0-3
reader #0  got  gen#1-3
<removed repetitive output>
reader #1  got  gen#0-2
Done!

但是有时候经过多次运行,我得到了:

reader #2  got  gen#0-3
reader #0  got  gen#1-3
<removed repetitive output>
reader #1  got  gen#0-2
Done!
reader #2  got  gen#0-4

为什么在“完成!”之后打印出一些内容? ?如您所见,我正等待阅读器和生成器完成,然后再打印“完成!”。

0 个答案:

没有答案