github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/perf/gopool/gopool.go (about) 1 // Copyright 2021 ByteDance Inc. 2 // Copyright 2023 Shawn Wang <jxskiss@126.com>. 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 // Package gopool is a high-performance goroutine pool which aims to reuse goroutines 17 // and limit the number of goroutines. 18 package gopool 19 20 import ( 21 "context" 22 "fmt" 23 "sync" 24 ) 25 26 var defaultPool *Pool 27 28 var poolMap sync.Map 29 30 func init() { 31 config := &Config{Name: "gopool.defaultPool"} 32 defaultPool = NewPool(config) 33 } 34 35 // Default returns the global default pool. 36 // The default pool does not enable permanent workers, 37 // it also does not limit the adhoc worker count. 38 // The package-level methods Go and CtxGo submit tasks to the default pool. 39 // 40 // Note that it's not recommended to change the worker limit 41 // of the default pool, which affects other code that use the default pool. 42 func Default() *Pool { 43 return defaultPool 44 } 45 46 // Go is an alternative to the go keyword, which is able to recover panic, 47 // reuse goroutine stack, limit goroutine numbers, etc. 48 // 49 // See package doc for detailed introduction. 50 func Go(f func()) { 51 defaultPool.CtxGo(context.Background(), f) 52 } 53 54 // CtxGo is preferred over Go. 55 func CtxGo(ctx context.Context, f func()) { 56 defaultPool.CtxGo(ctx, f) 57 } 58 59 // Register registers a Pool to the global map, 60 // it returns error if the same name has already been registered. 61 // To register a pool, the pool should be configured with a 62 // non-empty name. 63 // 64 // Get can be used to get the registered pool by name. 65 func Register(p *Pool) error { 66 _, loaded := poolMap.LoadOrStore(p.Name(), p) 67 if loaded { 68 return fmt.Errorf("pool %s already registered", p.Name()) 69 } 70 return nil 71 } 72 73 // Get gets a registered Pool by name. 74 // It returns nil if specified pool is not registered. 75 func Get(name string) *Pool { 76 p, ok := poolMap.Load(name) 77 if !ok { 78 return nil 79 } 80 return p.(*Pool) 81 }