lancet icon indicating copy to clipboard operation
lancet copied to clipboard

Promise内存布局优化,以及内存固定bug

Open lee157953 opened this issue 1 year ago • 1 comments

Promise由于其特殊性,必须是pin的,不能够移动在内存中的位置,所以new函数返回一个Promise指针依旧有可能不安全,且sync.Mutex和sync.WaitGroup虽然为了内存不可移动声明为指针类型,但是占用了更多内存,且*sync.Mutex是不必要的,建议将代码修改为如下布局,更安全,并节约资源

type Promise[T any] struct {
	*promise[T]
}

type promise[T any] struct {
	runnable func(resolve func(T), reject func(error))
	result   T
	err      error
	wait     sync.WaitGroup
	pending  atomic.Bool
}

lee157953 avatar Nov 08 '23 09:11 lee157953

Promise由于其特殊性,必须是pin的,不能够移动在内存中的位置,所以new函数返回一个Promise指针依旧有可能不安全,且_sync.Mutex和_sync.WaitGroup虽然为了内存不可移动声明为指针类型,但是占用了更多内存,且*sync.Mutex是不必要的,建议将代码修改为如下布局,更安全,并节约资源

type Promise[T any] struct {
	*promise[T]
}

type promise[T any] struct {
	runnable func(resolve func(T), reject func(error))
	result   T
	err      error
	wait       sync.WaitGroup
	pending  atomic.Bool
}

@lee157953 赞👍,可以提个pr.

duke-git avatar Nov 09 '23 04:11 duke-git