在他对这个问题的回答中:Golang for Windows erratic behavior? 建议USER@DISTRIBTED锁定/同步访问并发Goroutine上的共享变量.
我怎么才能做到这一点呢?
有关这个问题的更多信息:
我让这段代码(闭包为views
的返回函数)同时在几个goroutine上运行:
func makeHomeHandler() func(c *http.Conn, r *http.Request) {
views := 1
return func(c *http.Conn, r *http.Request) {
fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views)
views++
}
}
看起来IO函数花了很长时间,结果我得到了这样的输出:
Counting monkeys, 5 so far.
Counting monkeys, 5 so far.
Counting monkeys, 5 so far.
Counting monkeys, 8 so far.
Counting monkeys, 8 so far.
Counting monkeys, 8 so far.
Counting monkeys, 11 so far.
它可以很好地递增,但是当它被打印出来时,我可以看到打印+递增操作根本不是原子的.
如果我将其更改为:
func makeHomeHandler() func(c *http.Conn, r *http.Request) {
views := 0
return func(c *http.Conn, r *http.Request) {
views++
// I can only hope that other goroutine does not increment the counter
// at this point, i.e., right after the previous line and before the
// next one are executed!
views_now := views
fmt.Fprintf(c, "Counting %s, %d so far.", r.URL.Path[1:], views_now)
}
}
它似乎运行良好,但我不能完全肯定它最终是否不会失败……