douchao1864 2019-02-01 06:51
浏览 82

我们可以在goroutine中实现goroutine吗?

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.

  • 写回答

1条回答 默认 最新

  • duanluo9369 2019-02-01 07:03
    关注

    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()
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?