Search code examples
goatomicinteger-overflow

atomic AddUint32 overflow


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?


Solution

  • 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