doudou5101
doudou5101
2014-04-15 19:21

此Webapp代码是否需要同步?

  • goroutine
  • concurrency
已采纳

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条回答

  • duanhe7471 duanhe7471 7年前

    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.

    点赞 评论 复制链接分享

为你推荐