doudou5101 2014-04-15 19:21
浏览 4
已采纳

此Webapp代码是否需要同步?

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 2014-04-15 19:25
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度