go - 在 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)
}
}
我想问这个假设是否正确,以及通过简单地阻止例程退出无限循环来实现这一点是否现实。如果有人可以给我意见或引导我采用更好的方法,我将不胜感激
解决方案
推荐阅读
- c# - 无法在 C# 中使用上标
- function - 更好地表示性能数据。过滤功能?
- yocto - 我正在尝试在 yocto 中编译一个 bb 配方文件。我面临:make:***没有指定目标,也没有找到makefile。停止。错误
- apache-spark - 在 EMR 中运行时,Spark SFTP 库无法从 sftp 服务器下载文件
- java - 无需注释的休眠可嵌入
- android - 自定义适配器中未解决的引用
- xslt - XSLT 2.0 一组多级
- reactjs - React 组件在本地状态第一次更改时闪烁
- sql - Microsoft Access 小计百分比
- javascript - React Item.map 不是一个函数