How to use atomic.Int64?

1,056 views
Skip to first unread message

Benz

unread,
Sep 1, 2022, 7:29:28 AM9/1/22
to golang-nuts
Since go `1.19`, the [`atomic.Int64`](https://github.com/golang/go/blob/go1.19/src/sync/atomic/type.go#L82) was added

```go
type Int64 struct {
    _ noCopy
    _ align64
    v int64
}
```

There is one additional [`align64`](https://github.com/golang/go/blob/go1.19/src/sync/atomic/type.go#L191) in `atomic.Int64`

```go
// align64 may be added to structs that must be 64-bit aligned.
// This struct is recognized by a special case in the compiler
// and will not work if copied to any other package.
type align64 struct{}
```

With the test codes under go 1.19

```go
    var i64 int64
    var a64 atomic.Int64
    fmt.Println(unsafe.Alignof(i64))
    fmt.Println(unsafe.Alignof(a64))
```

The result is

```
8
8
```

The test environment is MacOS with CPU info

```
hw.ncpu: 12
hw.activecpu: 12
hw.perflevel0.cpusperl2: 2
hw.perflevel0.cpusperl3: 12
hw.perflevel0.logicalcpu: 12
hw.perflevel0.logicalcpu_max: 12
hw.perflevel0.physicalcpu: 6
hw.perflevel0.physicalcpu_max: 6
hw.cpu64bit_capable: 1
```

It seems both `int64` and `atomic.Int64` have the same align size `8`. What does `align64 may be added to structs that must be 64-bit aligned` means? What situations can `atomic.Int64` be used?

Axel Wagner

unread,
Sep 1, 2022, 8:15:29 AM9/1/22
to Benz, golang-nuts
I'm not sure under what situations you get misaligned values. But note that atomic.Int64 has other benefits besides alignment guarantees. Most importantly, it prevents you from accidentally mixing atomic and non-atomic accesses to the same address - every access of an atomic.Int64 is always atomic.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/c800d445-deb7-4683-b353-e1bc17d457abn%40googlegroups.com.

Keith Randall

unread,
Sep 2, 2022, 1:49:41 AM9/2/22
to golang-nuts
There's a difference only on platforms that wouldn't normally 8-byte align an int64. Those are the 32-bit platforms, e.g. linux/386. On those platforms your program prints 4 8.
Reply all
Reply to author
Forward
0 new messages