dongsimang4036 2017-02-10 15:21 采纳率: 100%
浏览 104
已采纳

循环内的互斥导致意外输出

I have this simplistic piece of code (or here https://play.golang.org/p/KW8_OHUp9v)

package main

import (
    "fmt"
    "sync"
)

func main() {
    mutex := new(sync.Mutex)

    for i := 1; i < 5; i++ {
        for j := 1; j < 5; j++ {
            mutex.Lock()
            go func() {
                fmt.Printf("%d + %d = %d
", i, j, j+i)
                mutex.Unlock()
            }()
        }
    }
}

It produces an output like this

1 + 2 = 3
1 + 3 = 4
1 + 4 = 5
2 + 5 = 7
2 + 2 = 4
2 + 3 = 5
2 + 4 = 6
3 + 5 = 8
3 + 2 = 5
3 + 3 = 6
3 + 4 = 7
4 + 5 = 9
4 + 2 = 6
4 + 3 = 7
4 + 4 = 8

Program exited.

Looking at the output I was surprised by few things:

  1. There are no '1's for the j
  2. There are '5's for the j
  3. There are only 3 values for i=1, instead of 4

I can understand lack of '1's as the variable is incremented before it is written.

Can someone explain 2. and 3. ?

  • 写回答

2条回答 默认 最新

  • dtjwov4984 2017-02-10 15:46
    关注

    You're closing over variables in a loop and then running the closure in a separate thread, while those variables continue to change. When you do this, expect the unexpected - for example, you see 5s because j is incremented to 5 on the last iteration, which causes the loop to end, but j still holds 5, which the separate thread can then read. It has nothing to do with your mutex; it's the cross-thread sharing of variables. If you use:

    go func(i,j int) {
        fmt.Printf("%d + %d = %d
    ", i, j, j+i)
        mutex.Unlock()
    }(i,j)
    

    Then it will pass in the values of i and j at the time your goroutine is started, and subsequent iterations won't affect it: https://play.golang.org/p/P3kUP5e1Fp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀