github.com/wfusion/gofusion@v1.1.14/routine/types.go (about) 1 package routine 2 3 import ( 4 "strconv" 5 "sync" 6 "time" 7 8 "github.com/wfusion/gofusion/common/utils" 9 "github.com/wfusion/gofusion/log" 10 ) 11 12 const ( 13 ErrTimeout utils.Error = "operation timed out" 14 ErrPoolOverload utils.Error = "too many goroutines blocked on submit or Nonblocking is set" 15 ErrDuplicatedName utils.Error = "duplicated goroutine pool name" 16 ) 17 18 var ( 19 // wg 用于简易协程的优雅退出 20 wg sync.WaitGroup 21 locker sync.RWMutex 22 routines = map[string]map[string]int{} 23 ) 24 25 type Pool interface { 26 Submit(task any, opts ...utils.OptionExtender) error 27 Running() int 28 Free() int 29 Waiting() int 30 Cap() int 31 IsClosed() bool 32 Release(opts ...utils.OptionExtender) 33 ReleaseTimeout(timeout time.Duration, opts ...utils.OptionExtender) error 34 } 35 36 // Conf routine configure 37 //nolint: revive // struct tag too long issue 38 type Conf struct { 39 // MaxGoroutineAmount 最大协程数量 40 MaxRoutineAmount int `yaml:"max_routine_amount" json:"max_routine_amount" toml:"max_routine_amount" default:"-1"` 41 42 // MaxReleaseTimePerPool 优雅退出时单个 pool 最大等待时间 43 MaxReleaseTimePerPool string `yaml:"max_release_time_per_pool" json:"max_release_time_per_pool" toml:"max_release_time_per_pool" default:"30s"` 44 45 // ForceSync will synchronously execute Go, promise function if true 46 ForceSync bool `yaml:"force_sync" json:"force_sync" toml:"force_sync" default:"false"` 47 48 // Logger is the customized logger for logging info, if it is not set, 49 // default standard logger from log package is used. 50 EnabledLogger bool `yaml:"enable_logger" json:"enable_logger" toml:"enable_logger" default:"false"` 51 Logger string `yaml:"logger" json:"logger" toml:"logger" default:"github.com/wfusion/gofusion/log/customlogger.routineLogger"` 52 LogInstance string `yaml:"log_instance" json:"log_instance" toml:"log_instance" default:"default"` 53 } 54 55 func addRoutine(appName, name string) { 56 locker.Lock() 57 defer locker.Unlock() 58 59 if _, ok := routines[appName]; !ok { 60 routines[appName] = make(map[string]int) 61 } 62 routines[appName][name]++ 63 } 64 65 func delRoutine(appName, name string) { 66 locker.Lock() 67 defer locker.Unlock() 68 if routines == nil || routines[appName] == nil { 69 return 70 } 71 72 if routines[appName][name]--; routines[appName][name] <= 0 { 73 delete(routines, name) 74 } 75 } 76 77 func showRoutine(appName string) (r []string) { 78 locker.RLock() 79 defer locker.RUnlock() 80 r = make([]string, 0, len(routines[appName])) 81 for n, c := range routines[appName] { 82 r = append(r, n+":"+strconv.Itoa(c)) 83 } 84 return 85 } 86 87 type customLogger interface { 88 Init(log log.Loggable, appName string) 89 }