问题描述
我需要在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 (将#修改为@)