Skip to content

Instantly share code, notes, and snippets.

@CAFxX
Created January 23, 2020 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CAFxX/f09d41820403854a643b875a9225807d to your computer and use it in GitHub Desktop.
Save CAFxX/f09d41820403854a643b875a9225807d to your computer and use it in GitHub Desktop.
aligned
package aligned
import (
"fmt"
"unsafe"
"golang.org/x/sys/cpu"
)
const (
cacheLineSize = unsafe.Sizeof(cpu.CacheLinePad{})
)
func malign(size, align uintptr) unsafe.Pointer {
s := align * 2
if size > align {
s = align * (1 + (size+align-1)/align)
}
b := make([]byte, s)
for i := range b[:uintptr(len(b))-size] {
p := (unsafe.Pointer)(&b[i])
if (uintptr)(p)%align == 0 {
return p
}
}
panic(fmt.Sprintf("mailgn(%d, %d): bug", size, align))
}
// Uint64 returns a cacheline-aligned uint64 that is guaranteed not
// to share the cacheline with any other data.
func Uint64() *uint64 {
return (*uint64)(malign(unsafe.Sizeof(uint64(0)), cacheLineSize))
}
// Int64 returns a cacheline-aligned int64 that is guaranteed not
// to share the cacheline with any other data.
func Int64() *int64 {
return (*int64)(malign(unsafe.Sizeof(int64(0)), cacheLineSize))
}
// Uint32 returns a cacheline-aligned uint32 that is guaranteed not
// to share the cacheline with any other data.
func Uint32() *uint32 {
return (*uint32)(malign(unsafe.Sizeof(uint32(0)), cacheLineSize))
}
// Int32 returns a cacheline-aligned int32 that is guaranteed not
// to share the cacheline with any other data.
func Int32() *int32 {
return (*int32)(malign(unsafe.Sizeof(int32(0)), cacheLineSize))
}
// Uintptr returns a cacheline-aligned uintptr that is guaranteed not
// to share the cacheline with any other data.
func Uintptr() *uintptr {
return (*uintptr)(malign(unsafe.Sizeof(uintptr(0)), cacheLineSize))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment