这个 webapp 的代码需要同步吗?

huangapple go评论98阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年4月16日 03:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/23092579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定