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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器