dtz30833 2019-03-16 16:00
浏览 143
已采纳

并发使用时,BufferedWriter不起作用

I need to write large amount of data to text file from a number of goroutines (say 30) concurrently. What I do is this:

workers.Add(core.Concurrency)
    for i := 0; i < core.Concurrency; i++ {
        go func() {
            defer workers.Done()
            writer := bufio.NewWriter(f)
            defer writer.Flush()
            a.Worker(workChan, writer)
        }()
    }

But this doesn't seems to work for some cases. Here f is the *os.File object. This doesn't writes to the file in some cases at all, and in some cases it writes some data but doesn't do future writes. The behaviour is very inconsistent and there are no errors too.

Any ideas why this might be happening?

  • 写回答

1条回答 默认 最新

  • dongqiang5932 2019-03-16 16:16
    关注

    The problem is that you have multiple goroutines trying to write to a file at once, without any synchronization. This will lead to an unpredicatable output order, and possibly lost writes. Using buffered I/O on top of that just helps to obscure the behavior.

    The best solution is to kick off a single goroutine that writes to your output (with or without buffered I/O, depending on your needs), and have all of your workers send the data to be written to the writing goroutine over a channel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: