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条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 如何预处理存在负值的样本数据,使其能够全都成为正的
      • ¥15 请问怎么通过css改变图片颜色
      • ¥15 c语言文件读取到结构体以及写入
      • ¥15 Blender: auto rig pro骨骼动画导出后变形穿模
      • ¥15 C51单片机的设计思路哈
      • ¥15 Linux脏牛提权漏洞
      • ¥15 为何我用uni-data-checkbox 标签在APP里调试无法显示?
      • ¥30 关于Stata软件OLS模型一些简单问题
      • ¥15 list分组填充数据
      • ¥15 python多进程与np数组与talib计算金融指标问题