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

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 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现