This question already has an answer here:
I'm trying to get into go and I'm facing a problem which appears when using go routines on a method of a struct. What I was expecting is that the code prints the following output:
Item 1 was asked if it's alive
Item 2 was asked if it's alive
But it's not printing anything. When I leave out the "go"routines (at struct1.isAlive()) it's working fine. How can I make the goroutines work?
package main
import (
"fmt"
)
type somestruct struct {
ID int
ItemName string
}
func (s *somestruct) isAlive() (alive bool) {
alive = true
fmt.Printf("%s was asked if it's alive
", s.ItemName)
return
}
func main() {
struct1 := somestruct{
ID:1,
ItemName:"Item 1"}
struct2 := somestruct{
ID:2,
ItemName:"Item 2"}
go struct1.isAlive()
go struct2.isAlive()
</div>
The Issue is that the program exits before the functions could execute and print out to stdout.
One simple fix is to wait for both of the go routines to finish and then exit from main function.
Here is a link that you can refer : https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/
here is your program implemented with WaitGroups
package main
import (
"fmt"
"sync"
)
type somestruct struct {
ID int
ItemName string
wg *sync.WaitGroup
}
func (s *somestruct) isAlive() (alive bool) {
defer s.wg.Done()
alive = true
fmt.Printf("%s was asked if it's alive
", s.ItemName)
return
}
func main() {
var wg sync.WaitGroup
wg.Add(2)
struct1 := somestruct{
ID: 1,
ItemName: "Item 1",
wg: &wg,
}
struct2 := somestruct{
ID: 2,
ItemName: "Item 2",
wg: &wg,
}
go struct1.isAlive()
go struct2.isAlive()
wg.Wait()
}