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