duanjie9630 2019-02-19 11:04
浏览 27
已采纳

同时写入/读取时是否应该关闭文件?

I'm making a server that can read/write from file concurrently(from goroutines populated by net/http handlers). I've created The following struct:

type transactionsFile struct {
    File  *os.File
    Mutex *sync.RWMutex
}

I'm initializing file once at the init() function. Should I close it somehow on each writing operation?

  • 写回答

1条回答 默认 最新

  • douzao2992 2019-02-19 11:25
    关注

    You can't write to a closed file, so if you close it after each write operation, you also have to (re)open it before each write.

    This would be quite inefficient. So instead leave it open, and only close it once your app is about to terminate (this is required because File.Write() does not guarantee that when it returns the data is written to disk). Since you're writing the file from HTTP handlers, you should implement graceful server termination, and close the file after that. See Server.Shutdown() for details.

    Also, if the purpose of your shared file writing is to create some kind of logger, you could take advantage of the log package, so you would not have to use a mutex. For details, see net/http set custom logger.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!