dongquelu1239 2018-05-18 17:09
浏览 129
已采纳

fmt.Println的问题与线程打印顺序不一致

Consider the following code

package main

import (  
    "fmt"
    "runtime"
    "sync"
)

func main() {
    messages := make(chan bool)
    var wg sync.WaitGroup
    var x = 1000

    wg.Add(runtime.NumCPU())
    for i := 0; i < runtime.NumCPU(); i++ {
        go func(x int) {
            defer wg.Done()
            var i = 0
            for i < x {
                i += 1
                fmt.Println(i * i)
            }
            messages <- true
        }(x)
    }

    go func() {
        for i := range messages {
            fmt.Println(i)
        }
    }()

    wg.Wait()
}

And the following last couple of line output

980100
982081
984064
true
988036
990025
992016
994009
996004
998001
1000000

Since message <- true is always at the end of a for loop and

    for i := range messages {
        fmt.Println(i)
    }

prints after the channel receive the message.

I expect true to be printed always at the end like

988036
990025
992016
994009
996004
998001
1000000
true

But I find that is only sometimes true, why is that?

  • 写回答

1条回答 默认 最新

  • doujiaochan7317 2018-05-18 17:36
    关注

    What you're doing is:

    1. Start a number of goroutines, equal to the number of CPUs on your system.
    2. Start one additional goroutine, which reads and prints the values from the messages channel.
    3. Wait for the goroutines from #1 to terminate
    4. Exit

    Because you're only waiting for the first batch of goroutines to terminate, there is no guarantee that all (or even any) of the messages values will be printed before the program terminates.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。