首页 > 解决方案 > 在 Go 中同时附加到文件

问题描述

我需要在 Go 中编写一段代码,这将允许多个 go 例程同时写入文件。从我目前的研究中,我在另一篇文章中看到了一个很好的建议,即使用一个实际处理文件访问的 go 例程,然后让几个 go 例程通过一个通道发送数据,基本上这些附加将是顺序的,因为单个例程将是访问文件。到目前为止,这就是我对这个功能进行原型设计的方式。

func ListenAndServe(ch chan dataStruct){
  
   data:= <-ch 
   // I only care about writing right now 
   // opening the file in read only I think is thread safe 
   Write(data)
}
func Write(data){// some logic to have the data written in the file}
func Read(id ){ // some logic to open the file in read only mode }
func main(){
  ch := make(chan dataStruct)
  // Would I have to start the function in its own routine like so before I begin handling 
  // the actual write/ read requests by spawning separate routines 
  // and then  ListenAndServe function would block on the channel until there is something ? 
  go ListenAndServe(ch)
  // here I would write some code for sending each request to a go routine
  
}

我还是新手,但是如果我遵循我发现的这个建议,那么在我看来,ListenAndServe 函数会在第一个请求完成后立即退出,因此我必须将 ListenAndServe 函数的内容包装在 for像这样循环:

func ListenAndServe(ch chan dataStruct){
 
for {
      data:= <-ch 
      Write(data)
   }
}

我想问这个假设是否正确,以及通过简单地阻止例程退出无限循环来实现这一点是否现实。如果有人可以给我意见或引导我采用更好的方法,我将不胜感激

标签: gofile-ioconcurrency

解决方案


推荐阅读