douying3251 2017-03-02 15:05
浏览 156
已采纳

原子AddUint32溢出

I'm using the below code to get unique IDs within process:

for i := 0; i < 10; i++ {
    go func() {
        for {
            atomic.AddUint32(&counter, 1)
            time.Sleep(time.Millisecond)
        }
    }()
}

What will happen if the counter value overflows uint32's limit?

  • 写回答

1条回答 默认 最新

  • duanhui1869 2017-03-02 15:12
    关注

    The value wraps around, which is very easy to demonstrate:

    u := uint32(math.MaxUint32)
    fmt.Println(u)
    u++
    fmt.Println(u)
    
    
    // or
    u = math.MaxUint32
    atomic.AddUint32(&u, 1)
    fmt.Println(u)
    

    https://play.golang.org/p/lCOM3nMYNc

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?