2
votes

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.

2
Except for the strange formatting, the code looks fine to me. You just need to call wg.Wait() somewhere. - Roland Illig
@RolandIllig yes but this is a example that I'm showing thanks for that - puneet55667788
Yes you can, did you run into some problem when you tried it, or did you not actually try it? - Adrian

2 Answers

1
votes

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()
}
0
votes

Actually, the word "implement" is not accurate. go is a keyword in Go language which is used before a Go function call to start a goroutine asynchronous. So you can start a goroutine almost anywhere with a valid Go function.

Only when a function is called with go before it, it's viewed as a goroutine. Otherwise, it's just a normal function.