Why is my gorutin not executed?

I am learning Go and I wanted to try goroutines and feeds.

Here is my code:

package main import "fmt" func main(){ messages := make(chan string,3) messages <- "one" messages <- "two" messages <- "three" go func(m *chan string) { fmt.Println("Entering the goroutine...") for { fmt.Println(<- *m) } }(&messages) fmt.Println("Done!") } 

And here is the result:

 Done! 

I don’t understand why my goroutine was never performed. "Input goroutine" is not printed, and I do not have an error message.

+7
go
source share
2 answers

The fact is that your goroutine starts, but ends before you do anything, because your program stops immediately after printing Done! : goroutines execution is independent of the main program, but will be stopped at the same time as the program. So basically you need some kind of process so that the program expects them. It may be another channel waiting for several messages, sync.WaitGroup or other tricks.

On the golang blog, you should read an excellent article on concurrency in go .

+15
source share

Your Goroutine does not have enough time to complete, since the main function ends after printing Done! .

You need to do something to make the program expect Goroutine.

The easiest way is to add time.Sleep() to the end.

 package main import ( "fmt" "time" ) func main() { messages := make(chan string, 3) messages <- "one" messages <- "two" messages <- "three" go func(m *chan string) { fmt.Println("Entering the goroutine...") for { fmt.Println(<-*m) } }(&messages) time.Sleep(5 * time.Second) fmt.Println("Done!") } 

Entering goroutine ... alone
two
three
Done!

Playground

While this works, it is recommended that you use the channels or functions from the sync package, in addition to goroutines, to synchronize parallel code.

Example:

 package main import ( "fmt" ) func main() { messages := make(chan string, 3) go func(m chan string) { defer close(m) fmt.Println("Entering the goroutine...") messages <- "one" messages <- "two" messages <- "three" }(messages) for message := range messages { fmt.Println("received", message) } fmt.Println("Done!") } 

Joining Gorutin ... got one got two
got three done!

Playground

+5
source share

All Articles