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

Issue

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?

Solution

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.

Answered By – Linear

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.