为什么这个代码不能用goroutine打印任何东西 [英] why doesn't this go code print anything with a goroutine

查看:141
本文介绍了为什么这个代码不能用goroutine打印任何东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定错过了一些关于goroutines的基本知识,但是我环顾四周,我看不出有什么理由不这么做......

I must be missing something really basic about goroutines, but I've looked around and I cannot see any reason why this would not work...

package main

import "fmt"

func main() {
    for i := 0; i < 20; i++ {
        //fmt.Println(i)
        go func(j int) {
            fmt.Println(j + 100)
        }(i)
    }
}


推荐答案

goroutines有机会运行。

Your program is finishing before your goroutines have a chance to run.

以下代码使用 WaitGroup

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 20; i++ {
        wg.Add(1)
        go func(j int) {
            defer wg.Done()
            fmt.Println(j + 100)
        }(i)
    }
    fmt.Println("Waiting...")
    wg.Wait()
    fmt.Println("Done.")
}

https://play.golang.org/p/lmCPU9-qkB

这篇关于为什么这个代码不能用goroutine打印任何东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆