Showing posts with label golang_atomic. Show all posts
Showing posts with label golang_atomic. Show all posts

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())
}

Apr 23, 2020

[Go] is assign value to pointer an atomic operation?

Discussion thread:
https://groups.google.com/forum/#!msg/golang-nuts/MgIP2KvEAaU/dor44Kq5BAAJ

In system languages it should, however, in C++, consider pointer to member function is 2-word size, which can not be atomic.

That is to say, in Go, quote from Ian Lance Taylor,
both pointer assignments and uintptr assignments are done in a way that can not be interrupted.

2020 project, pick up Rust~