I'm learning Go and I wanted to try goroutines and channels.
Here's 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's the result:
Done!
I don't understand why my goroutine is never executed. The "Entering the goroutine" is not printed and I don't have any error message.
The fact is that your goroutine starts, but is ended before doing anything because your program stop right after printing Done!
: execution of goroutines is independant of the main program, but will be stopped at the same than the program. So basically, you need some process to make the program wait for them. It could be another channel waiting for a number of messages, a sync.WaitGroup
, or other tricks.
You should read the excellent post about concurrency in go in the golang blog.
Your Goroutine doesn't have enough time to execute, as the main function exits after printing Done!
.
You need to do something to make the program wait for the Goroutine.
The easiest way is to add a 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 the goroutine...
one
two
three
Done!
Playground
While this works, it's recommended to use channels, or functions from the sync
package, in addition to goroutines, to synchronize concurrent 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!")
}
Entering the goroutine...
received one
received two
received three
Done!
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With