I'm using goroutines in the function because I want when the function will start then the quires of database also run on that time. But there is a question I'm asking that Can we implement a goroutine in the other goroutine because in the function I already set a go routine but in that go routine there are to queries more and I want that they also run when the parent goroutine starts. Example
func main(){
wg := &sync.WaitGroup{}
wg.Add(1)
go func(){
defer wg.Done()
Id,err := QueryWhichWillReturnId()
if err == nil{
wg.Add(1)
go func(){
defer wg.Done()
data:= GetAnyDataById(Id)
fmt.Println(data)
}()
}
}()
wg.Wait()
}
Is this above example is possible while implementing goroutines?
any suggestions will appreciated.
goroutine can be start from a parant goroutine.Once goroutineB starts from goroutineA, they runs the same weigh.
There are a thing for you to consider if you want to do like this.
Is my new goroutine neccessary to start?
I give you an example that a query request need to be saved both to database and a remote log server. Two saving steps are parallel and no interference. Then it's good to start 2 goroutine. One to save to database, one to save to log server.Now you look at your query. GetAnyDataById(Id)
,apparantly your new routine query depends on your former query result form QueryWhichWillReturnId()
, are they none-interfere? are they logical parallel? Neither, so this is a bad spot to use goroutine.
Last, you wg.Add(1)
, but you wg.Done()
twice, it will panic.
Can we implement a goroutine inside a goroutine? yes. you can use go func(){}()
wherever you want to start a new goroutine.
func main(){
wg := &sync.WaitGroup{}
wg.Add(1)
go func(){
defer wg.Done()
Id,err := QueryWhichWillReturnId()
if err != nil{
fmt.Println(err.Error())
return
}
data:= GetAnyDataById(Id)
fmt.Println(data)
}()
wg.Wait()
}