diff --git a/asyncLocal/newAsyncLocal.go b/asyncLocal/newAsyncLocal.go index 705075053..4f583b926 100644 --- a/asyncLocal/newAsyncLocal.go +++ b/asyncLocal/newAsyncLocal.go @@ -4,27 +4,21 @@ import ( "github.com/timandy/routine" ) +var list []routine.ThreadLocal + type AsyncLocal[T any] struct { threadLocal routine.ThreadLocal } -// 将同一个协程所New的AsyncLocal放到同一个数组中,在使用完后释放 -var list = make(map[int64][]routine.ThreadLocal) - // New 创建一个AsyncLocal func New[T any]() AsyncLocal[T] { // 加入到list集合,用于手动GC - al := AsyncLocal[T]{ - threadLocal: routine.NewInheritableThreadLocal(), - } - al.AddRelease() - return al -} + threadLocal := routine.NewInheritableThreadLocal() + list = append(list, threadLocal) -// AddRelease 将同一个协程所New的AsyncLocal放到同一个数组中,在使用完后自动释放 -func (receiver AsyncLocal[T]) AddRelease() { - goId := routine.Goid() - list[goId] = append(list[goId], receiver.threadLocal) + return AsyncLocal[T]{ + threadLocal: threadLocal, + } } // Get 获取值 @@ -47,11 +41,10 @@ func (receiver AsyncLocal[T]) Remove() { receiver.threadLocal.Remove() } -// Release 释放当前使用的AsyncLocal +// Release 释放 func Release() { - goId := routine.Goid() - for _, threadLocal := range list[goId] { + for _, threadLocal := range list { threadLocal.Remove() } - delete(list, goId) + routineContext.Remove() }