doumei1203 2018-01-10 12:50
浏览 111
已采纳

我无法在for循环中同时写入文件-Goroutine无法正常工作

My Go project breaks when I try to write concurrently.

I have a map map[string][]strings. I want to write files concurrently, which are named as key + ".csv" and for each value of []strings write another row to the file with the value in it.

What I've done:

for key, val := range varValMap {
        go writeCsv(key, val)
    }

And the func is:

func writeCsv(variable string, values []string) {
    fName := variable + ".csv"
    fPath := filepath.Join(xmlFolder, "_varval", fName)
    file, err := os.Create(fPath)
    check(err)
    defer file.Close()
    for _, value := range values {
        fmt.Fprintf(file, value + "
")
    }
}

The program finishes with no problems detectable by me, yet with no complete result (some files are written but nothing in them), also when I remove go from go writeCsv(key, val) all is well in go land.

  • 写回答

1条回答 默认 最新

  • duanqiao3608 2018-01-10 12:59
    关注

    You're not waiting for your goroutines to finish. This means that as soon as your for loop is done launching all the goroutines, the program exits. Any goroutine still running is aborted.

    You can use a sync.WaitGroup as a simple way to wait for execution to be finished:

    var wg sync.WaitGroup
    for key, val := range varValMap {
        wg.Add(1)
        go writeCsv(&wg, key, val)
    }
    wg.Wait()
    

    And change your writeCsv to notify the wait group:

    func writeCsv(wg *sync.WaitGroup, variable string, values []string) {
        defer wg.Done()
        // do everything.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题