Mar 25, 2021

[Go][ticket][trick] make 64-bit fields 64-bit aligned on 32-bit systems

Ticket:
cmd/compile: make 64-bit fields 64-bit aligned on 32-bit systems
https://github.com/golang/go/issues/599

Reference:


The idea below is to avoid any padding, thus using 15 bytes, which if using 14 bytes will be used by later 2 bytes short type.
package mylib

import (
	"unsafe"
	"sync/atomic"
)

type Counter struct {
	x [15]byte // instead of "x uint64"
}

func (c *Counter) xAddr() *uint64 {
	// The return must be 8-byte aligned.
	return (*uint64)(unsafe.Pointer(
		uintptr(unsafe.Pointer(&c.x)) + 8 -
		uintptr(unsafe.Pointer(&c.x))%8))
}

func (c *Counter) Add(delta uint64) {
	p := c.xAddr()
	atomic.AddUint64(p, delta)
}

func (c *Counter) Value() uint64 {
	return atomic.LoadUint64(c.xAddr())
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.