In his answer to this question: Golang for Windows erratic behavior? user @distributed recommended to lock/synchronize access to a shared variable on concurrent goroutines.
我怎样才能做到呢?
有关这个问题的更多情况是:
我得到这个代码( 返回函数, 在 < code> views 上关闭), 同时运行于多个网路 :
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)
}
}
似乎还行 但我不能完全确定它是否会最终失败...