gopoll.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2021 ByteDance Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package gopool
  15. import (
  16. "context"
  17. "fmt"
  18. "sync"
  19. )
  20. // defaultPool is the global default pool.
  21. var defaultPool Pool
  22. var poolMap sync.Map
  23. func init() {
  24. defaultPool = NewPool("gopool.DefaultPool", 10000, NewConfig())
  25. }
  26. // Go is an alternative to the go keyword, which is able to recover panic.
  27. //
  28. // gopool.Go(func(arg interface{}){
  29. // ...
  30. // }(nil))
  31. func Go(f func()) {
  32. CtxGo(context.Background(), f)
  33. }
  34. // CtxGo is preferred than Go.
  35. func CtxGo(ctx context.Context, f func()) {
  36. defaultPool.CtxGo(ctx, f)
  37. }
  38. // SetCap is not recommended to be called, this func changes the global pool's capacity which will affect other callers.
  39. func SetCap(cap int32) {
  40. defaultPool.SetCap(cap)
  41. }
  42. // SetPanicHandler sets the panic handler for the global pool.
  43. func SetPanicHandler(f func(context.Context, interface{})) {
  44. defaultPool.SetPanicHandler(f)
  45. }
  46. // WorkerCount returns the number of global default pool's running workers
  47. func WorkerCount() int32 {
  48. return defaultPool.WorkerCount()
  49. }
  50. // RegisterPool registers a new pool to the global map.
  51. // GetPool can be used to get the registered pool by name.
  52. // returns error if the same name is registered.
  53. func RegisterPool(p Pool) error {
  54. _, loaded := poolMap.LoadOrStore(p.Name(), p)
  55. if loaded {
  56. return fmt.Errorf("name: %s already registered", p.Name())
  57. }
  58. return nil
  59. }
  60. // GetPool gets the registered pool by name.
  61. // Returns nil if not registered.
  62. func GetPool(name string) Pool {
  63. p, ok := poolMap.Load(name)
  64. if !ok {
  65. return nil
  66. }
  67. return p.(Pool)
  68. }