如何解决在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)
}
}
我想问这个假设是否正确,是否可以通过简单地阻止例程以无限循环退出来实现这一假设。 如果有人可以给我意见或指导我采取更好的方法,我将不胜感激
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。