英文:
Does this webapp code need synchronization?
问题
我正在学习Go语言,这是我正在编写的一个Web应用程序的代码:
func init() {
db, err := sql.Open("mysql", "master:123456@/shopping_list")
if err != nil {
panic(err.Error())
}
http.HandleFunc("/sql", func(w http.ResponseWriter, r *http.Request) {
sqlHandler(w, r, db)
})
}
sqlHandler()
函数从shopping_list表中读取一条记录,对其进行编辑,然后更新该记录。
据我了解,每个请求在单独的goroutine中运行,而mysql在读取或写入记录时会锁定该记录。那么,在这种情况下,这段代码是否需要任何同步操作呢?
英文:
I'm learning Go at the moment and this is the code for a web-app I'm writing:
func init() {
db, err := sql.Open("mysql", "master:123456@/shopping_list")
if err != nil {
panic(err.Error())
}
http.HandleFunc("/sql", func(w http.ResponseWriter, r *http.Request) {
sqlHandler(w, r, db)
})
}
sqlHandler()
reads a record from a table in shopping_list, edits it and then updates the record.
Now as I understand it, each request runs on a separate goroutine and that mysql locks a record while it is being read or written. So, in this case, does this code need any synchronization?
答案1
得分: 2
简短回答:不需要。
你不需要显式地同步你的代码,因为对db
上的任何需要锁的方法的调用都会简单地阻塞,直到锁被释放。换句话说,同步由实际需要同步的包来处理。
另外,我建议你通过gofmt
运行你的代码,这将使其他阅读你代码的Go爱好者感到满意。
英文:
Short answer: no.
You don't need to explicitly synchronise your code, because calls to any method on db
that require a lock will simply block until the lock is released. In other words, synchronisation is taken care of by the package that actually needs the synchronisation.
As a side note, I would suggest to run your code through gofmt
, which will make other Go nuts who read your code happy.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论