arena

package module
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2024 License: BSD-3-Clause Imports: 3 Imported by: 0

README

arena

English

介绍

go1.20引入了arena.Arena,但不能同时被多个goroutine使用,且go1.n(n<20)不能使用,本包提供解除这些限制的Arena

特点
  • 可以同时在多个goroutine使用
  • 可以在版本低于go1.20使用 (>=go1.18)
  • 不会发生释放后使用

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Alloc added in v0.3.0

func Alloc[T any](a *Arena, bufsize ...int64) *T

Alloc 从 *Arena 中创建一个 T , 并返回指针

  • bufsize 是可选的,决定 MemPool.Alloc 每次自动扩容分配多大内存,默认为8Mb,必须大于unsafe.Sizeof(*new(T))

func AllocSlice added in v0.3.0

func AllocSlice[T any](a *Arena, len, cap int, bufsize ...int64) []T

Alloc 从 *Arena 中创建一些连续的 T , 并返回切片

  • bufsize 是可选的,决定 MemPool.AllocSlice 每次自动扩容分配多大内存,默认为8Mb,必须大于unsafe.Sizeof(*new(T))*uintptr(cap)

func AllocSoonUse added in v0.8.0

func AllocSoonUse[T any](a *Arena, bufsize ...int64) *T

AllocSoonUse 从 *Arena 中创建一个 T , 并返回指针

  • bufsize 是可选的,决定 MemPool.Alloc 每次自动扩容分配多大内存,默认为8Mb,必须大于unsafe.Sizeof(*new(T))

对这个函数的多次调用将尽可能把返回的指针指向接近的内存地址,以提高很快就要使用的一批不同类型数据的缓存命中率

请勿从此函数分配含有指针的类型,否则分配出的内存将对GC隐藏这个类型的对象中的指针,这可能导致一些还在使用的内存被GC回收

func UseAfterFree added in v0.5.0

func UseAfterFree(enable bool)

EnableUseAfterFree 使得 *Arena*MemPool 可以发生 use-after-free (释放后使用) 来优化性能

因为只要有一个 *Arena*MemPool 可以发生 use-after-free (释放后使用) 就不能保证不发生数据竞争等问题 所以设计成 use-after-free (释放后使用) 不是不会发生就是都有可能发生

Types

type Arena

type Arena struct {
	// contains filtered or unexported fields
}

Arena是go1.20引入的arena.Arena的升级替代

它通过为每个类型准备内存池实现

与go1.20引入的arena.Arena相比,有下列不同

  • 可以同时在多个goroutine使用
  • 可以在版本低于go1.20使用
  • 不会发生释放后使用

创建后不得复制

Example
type user struct {
	a, b, c int
}
a := New()
//分配并使用
b := Alloc[user](a)
b.a = 1
b.c = 2
//使用完毕
a.Free()
Output:

func New added in v0.3.0

func New() *Arena

New创建一个 *Arena

func (*Arena) Free

func (a *Arena) Free()

Free 释放所有内存,只能调用一次,否则行为未定义

type MemPool added in v0.3.0

type MemPool[T any] struct {
	// contains filtered or unexported fields
}

func NewMemPool added in v0.3.0

func NewMemPool[T any](dataSize uintptr, rtype uintptr, bufsize ...int64) *MemPool[T]

NewMemPool 创建一组代表一起分配和释放的Go值的内存池

  • dataSize 是单个Go值大小,单位是字节
  • rtype 是go类型T的 *runtime._type
  • bufsize 是可选的,决定 MemPool 每次自动扩容分配多大内存,默认为8Mb,必须大于dataSize

func (*MemPool[T]) Alloc added in v0.3.0

func (a *MemPool[T]) Alloc() *T

Alloc 分配一个Go值,并返回指针

func (*MemPool[T]) AllocSlice added in v0.3.0

func (a *MemPool[T]) AllocSlice(len, cap int) []T

AllocSlice 分配连续的go值,并返回切片

func (*MemPool[T]) Free added in v0.3.0

func (a *MemPool[T]) Free()

Free 释放所有Go值

从调用的一刻开始,通过 MemPool.AllocMemPool.AllocSlice 获取的Go值,读写内存,行为是未定义且不安全的

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL