doutan1875 2018-01-09 05:20
浏览 62
已采纳

如何针对循环中的每次迭代重复调用函数,获取其结果,然后将结果附加到切片中(Golang?

I have the ff:

func getSlice(distinctSymbols []string) []symbols {
    // Prepare connection
    stmt1, err := db.Prepare("Select count(*) from stockticker_daily where symbol = $1;")
    checkError(err)
    defer stmt1.Close()
    stmt2, err := db.Prepare("Select date from stockticker_daily where symbol = $1 order by date asc limit 1;")
    checkError(err)
    defer stmt2.Close()
    var symbolsSlice []symbols
    c := make(chan symbols)
    for _, symbol := range distinctSymbols {
        go worker(symbol, stmt1, stmt2, c)
        **symbolsFromChannel := <-c**
        **symbolsSlice = append(symbolsSlice, symbolsFromChannel})**
    }
    return symbolsSlice
}

func worker(symbol string, stmt1 *sql.Stmt, stmt2 *sql.Stmt, symbolsChan chan symbols) {
    var countdp int
    var earliestdate string
    row := stmt1.QueryRow(symbol)
    if err := row.Scan(&countdp); err != nil {
        log.Fatal(err)
    }
    row = stmt2.QueryRow(symbol)
    if err := row.Scan(&earliestdate); err != nil {
        log.Fatal(err)
    }
    symbolsChan <- symbols{symbol, countdp, earliestdate}
}

Please take a look at the first function, I know it won't work as I expect since the line symbolsFromChannel := <-c will block until it receives from the channel, so the iteration on the goroutine go worker will not continue unless the block is removed. What is the best or correct way to do that?

  • 写回答

1条回答 默认 最新

  • dongyongkui6329 2018-01-09 05:30
    关注

    Just do the loop twice, e.g.

    for _, symbol := range distinctSymbols {
            go worker(symbol, stmt1, stmt2, c)
    }
    for range distinctSymbols {
            symbolsSlice = append(symbolsSlice, <-c)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要