douhuike3199 2019-02-07 17:12
浏览 16

为什么我的for循环仅在我放慢速度时才起作用?

This code prints 0, but if I insert time.Sleep(0) into the updater loop, it prints >1

var Nonce int = 0

func Updater(){
    for{
        Nonce += 1
    }
}

func main(){
    go Updater()
    time.Sleep(time.Second)
    fmt.Printf("%d
",Nonce)
}
  • 写回答

2条回答 默认 最新

  • douxiandiyo58855 2019-02-07 17:28
    关注

    Your main function spins up a goroutine to run Updater and then immediately exits. Without the sleep, Updater doesn't have time to start and do its thing. This code is racy - it will sometimes work as you expect and sometimes won't. You have to synchronize the Updater goroutine with main somehow, using a channel or a wait group for example.

    Moreover, you're updating the Nonce global in one goroutine and reading it in another - this is a data race. You'll need to synchronize access to this var with a mutex.


    Here's a more correct variant of your code, though it's still rather non-sensical (why do you need a goroutine to run the busy loop?)

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    var Nonce int = 0
    
    func Updater(wg *sync.WaitGroup) {
        defer wg.Done()
        for i := 0; i < 1000; i++ {
            Nonce += 1
        }
    }
    
    func main() {
        var wg sync.WaitGroup
        wg.Add(1)
        go Updater(&wg)
        wg.Wait()
        fmt.Printf("%d
    ", Nonce)
    }
    

    Here we use a WaitGroup for the Updater to signal "I'm done" to the main goroutine, which only then checks the value of Nonce. This program should print "1000" every time

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算