在一个包中定义的方法中调用的 Goroutine 不会运行。

huangapple go评论70阅读模式
英文:

Goroutine invoked in a method defined in a package does not run

问题

我只会为你提供翻译服务,以下是你要翻译的内容:

我只是想知道,如果在一个包中定义的方法中调用了一个goroutine,它可能不会运行。

这是我示例程序的结构:

sample
├── abc
│ └── abc.go
└── main.go

以下是abc.go和main.go的源代码

abc.go

1 package abc
2 
3 import (
4   "fmt"
5 )
6 
7 func PrintCde() {
8   fmt.Println("Cde")
9 }
10 
11 
12 type Abc struct {}
13 
14 func (a Abc)PrintAbc() {
15   fmt.Println("Abc")
16   go PrintCde()
17   for {}
18 }

main.go

1 package main
2 
3 import (
4   "sample/abc"
5 )
6 
7 func main() {
8   var a abc.Abc
9   a.PrintAbc()
10 
11 }

然后,如果我运行程序,我永远不会在屏幕上看到字符串"Cde"。

我猜测的原因是PrintAbc方法中的无限循环占用了计算资源,导致PrintCde函数无法被调度运行。

如果这是原因,是否有其他方法可以防止PrintAbc方法返回,但不占用资源以便让PrintCde函数运行?

英文:

I am just wondering that if a goroutine invoked in a method which is defined in a package may not run.

Here is the structure my sample program:

sample
├── abc
│   └── abc.go
└── main.go

And the following is the source code of abc.go and main.go

abc.go

1 package abc
2 
3 import (
4   "fmt"
5 )
6 
7 func PrintCde() {
8   fmt.Println("Cde")
9 }
10 
11 
12 type Abc struct {}
13 
14 func (a Abc)PrintAbc() {
15   fmt.Println("Abc")
16   go PrintCde()
17   for {}
18 }

main.go

1 package main
2 
3 import (
4   "sample/abc"
5 )
6 
7 func main() {
8   var a abc.Abc
9   a.PrintAbc()
10 
11 }

Then if I run the program, I never get the string "Cde" printed on the screen.

What I can guess is the for loop in the method PrintAbc occupies the computing resources and function PrintCde never got scheduled to run.

If this is the reason, is there any other ways to prevent
the method PrintAbc from retruning but not occupy the resources to let function printCde run?

答案1

得分: 1

是的,一个空/无限的for循环通常会导致这个问题。为了解决这个问题,可以使用空的select{}语句,它是一个阻塞操作,会促使/强制运行时切换 Goroutines。其他选项包括增加 GOMAXPROCS 或者(在一个真实的程序中)使用类似sync.WaitGroup的机制,在另一个 Goroutine 处理完成之前等待,然后自然地终止程序。

英文:

Yes, an empty/infinite for will generally cause this problem. For this purpose, use the empty select{} which is a blocking operation instead, and will encourage/force the runtime to swap Goroutines. Other options include increasing GOMAXPROCS or (in a real program) using something like a sync.WaitGroup to wait until the other Goroutine has finished processing before naturally terminating the program.

huangapple
  • 本文由 发表于 2014年6月25日 00:26:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/24391738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定