go - 在 Golang 中使用 goroutine 时遇到问题

标签 go goroutine

package main

import (
    "fmt"
    //-"time"
)

func main() {
    c:=make(chan int)
    for i:=0;i<1000;i++{
        go func() {
            fmt.Println(<-c)
        }()
    }
    for j:=0;j<1000;j++{
        c<-j
        //-time.Sleep(time.Second/100)
    }
}

当我运行这个程序时,它只打印大约一百个数字。
为什么它没有打印 1000 个数字?

但是当我没有注释图片中的代码时,结果变成了我的预期。哪里有问题?

最佳答案

Goroutines are similar to 'background jobs' :

The main Goroutine should be running for any other Goroutines to run. If the main Goroutine terminates then the program will be terminated and no other Goroutine will run.



在 channel “c”上等待消息的 1000 个 goroutine 正在“后台”中运行。主线程向 channel “c”发送 1000 条消息并立即终止。

100 个左右的整数输出将是不确定的,因为只要主线程需要将 1000 个整数发送到 channel “c”,你的 1000 个 goroutine 中的每一个才会存活。您需要主线程等待 1000 个 goroutine 完成。尝试使用 sync.WaitGroup目的:
package main

import (
    "fmt"
    "sync"
    //-"time"
)

func main() {
    wg := sync.WaitGroup{}
    c:=make(chan int)
    for i:=0;i<1000;i++{
        wg.Add(1)
        go func() {
            fmt.Println(<-c)
            wg.Done()
        }()
    }
    for j:=0;j<1000;j++{
        c<-j
        //-time.Sleep(time.Second/100)
    }
    wg.Wait()
}

关于go - 在 Golang 中使用 goroutine 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53314697/

相关文章:

memory-leaks - Golang Goroutine 泄漏

go - 在 Script 部分的 .gitlab-ci.yml 中调用 GO 二进制文件并捕获响应

Golang - 单独运行时长

go - 有 time.Sleep() 的无限循环与没有 time.Sleep() 的无限循环

c++ - 在C++中使用Go

go run 使用陈旧版本的子包

time - 戈朗 : throttle (time delay) function is not working in goroutine (works fine in main thread)

go - 超时停止 goroutine 执行

go - 所有 go routines 都睡着了 - 死锁

go - 如果并发进程向全局变量写入相同的值会发生什么?