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/