Initial QSfera import
This commit is contained in:
+22
@@ -0,0 +1,22 @@
|
||||
package syncs
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Go is a basic promise implementation: it wraps calls a function in a goroutine
|
||||
// and returns a channel which will later return the function's return value.
|
||||
//
|
||||
// if panic happen, it will be recovered and return as error
|
||||
func Go(f func() error) error {
|
||||
ch := make(chan error)
|
||||
go func() {
|
||||
// add recovery handle
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ch <- fmt.Errorf("panic recover: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
ch <- f()
|
||||
}()
|
||||
return <-ch
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package syncs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
// ErrGroup is a collection of goroutines working on subtasks that
|
||||
// are part of the same overall task.
|
||||
//
|
||||
// Refers:
|
||||
//
|
||||
// https://github.com/neilotoole/errgroup
|
||||
// https://github.com/fatih/semgroup
|
||||
type ErrGroup struct {
|
||||
*errgroup.Group
|
||||
}
|
||||
|
||||
// NewCtxErrGroup instance
|
||||
func NewCtxErrGroup(ctx context.Context, limit ...int) (*ErrGroup, context.Context) {
|
||||
egg, ctx1 := errgroup.WithContext(ctx)
|
||||
if len(limit) > 0 && limit[0] > 0 {
|
||||
egg.SetLimit(limit[0])
|
||||
}
|
||||
|
||||
eg := &ErrGroup{Group: egg}
|
||||
return eg, ctx1
|
||||
}
|
||||
|
||||
// NewErrGroup instance
|
||||
func NewErrGroup(limit ...int) *ErrGroup {
|
||||
eg := &ErrGroup{Group: new(errgroup.Group)}
|
||||
|
||||
if len(limit) > 0 && limit[0] > 0 {
|
||||
eg.SetLimit(limit[0])
|
||||
}
|
||||
return eg
|
||||
}
|
||||
|
||||
// Add one or more handler at once
|
||||
func (g *ErrGroup) Add(handlers ...func() error) {
|
||||
for _, handler := range handlers {
|
||||
g.Go(handler)
|
||||
}
|
||||
}
|
||||
|
||||
// Go add a handler function. if panic occurs, will catch it and return as error
|
||||
func (g *ErrGroup) Go(fn func() error) {
|
||||
// Group.Go: 调用给定函数的新流程。
|
||||
// 第一次“离开”的调用必须在等待之前发生。它会一直阻塞,直到新 goroutine 能够被添加,而该组中活跃 goroutine 数量不超过配置限制。
|
||||
// 第一次返回非零错误的调用会取消该组的上下文,如果该组是由调用 WithContext 创建的。错误将由等待返回。
|
||||
g.Group.Go(func() (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("panic recover: %v", r)
|
||||
}
|
||||
}()
|
||||
err = fn()
|
||||
return
|
||||
})
|
||||
}
|
||||
|
||||
// TryGo calls the given function in a new goroutine only if the number of
|
||||
// active goroutines in the group is currently below the configured limit.
|
||||
//
|
||||
// The return value reports whether the goroutine was started.
|
||||
//
|
||||
// If panic occurs, will catch it and return as error
|
||||
func (g *ErrGroup) TryGo(fn func() error) bool {
|
||||
// 只有当组中当前活跃的 goroutine 数量低于配置限制时,才会在新的 Goroutine 中调用该函数。
|
||||
// 返回值报告是否启动了goroutine。
|
||||
return g.Group.TryGo(func() (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("panic recover: %v", r)
|
||||
}
|
||||
}()
|
||||
err = fn()
|
||||
return
|
||||
})
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package syncs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// WaitCloseSignals for some huang program.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// // do something. eg: start a http server
|
||||
//
|
||||
// syncs.WaitCloseSignals(func(sig os.Signal) {
|
||||
// // do something on shutdown. eg: close db, flush logs
|
||||
// })
|
||||
func WaitCloseSignals(onClose func(sig os.Signal), sigCh ...chan os.Signal) {
|
||||
var signals chan os.Signal
|
||||
if len(sigCh) > 0 && sigCh[0] != nil {
|
||||
signals = sigCh[0]
|
||||
} else {
|
||||
signals = make(chan os.Signal, 1)
|
||||
}
|
||||
|
||||
signal.Notify(signals, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
// block until a signal is received.
|
||||
onClose(<-signals)
|
||||
close(signals)
|
||||
}
|
||||
|
||||
// SignalHandler returns an actor, i.e. an execute and interrupt func, that
|
||||
// terminates with SignalError when the process receives one of the provided
|
||||
// signals, or the parent context is canceled.
|
||||
//
|
||||
// from https://github.com/oklog/run/blob/master/actors.go
|
||||
func SignalHandler(ctx context.Context, signals ...os.Signal) (execute func() error, interrupt func(error)) {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
return func() error {
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, signals...)
|
||||
defer signal.Stop(c)
|
||||
|
||||
select {
|
||||
case sig := <-c:
|
||||
return SignalError{Signal: sig}
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}, func(error) {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// SignalError is returned by the signal handler's execute function
|
||||
// when it terminates due to a received signal.
|
||||
type SignalError struct {
|
||||
Signal os.Signal
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e SignalError) Error() string {
|
||||
return fmt.Sprintf("received signal %s", e.Signal)
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
// Package syncs provides synchronization primitives util functions.
|
||||
package syncs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// WaitGroup is a wrapper of sync.WaitGroup.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// wg := syncs.WaitGroup{}
|
||||
// wg.Go(func() {
|
||||
// time.Sleep(time.Second)
|
||||
// })
|
||||
// wg.Wait()
|
||||
//
|
||||
type WaitGroup struct {
|
||||
sync.WaitGroup
|
||||
}
|
||||
|
||||
// Go runs the given function in a new goroutine. will auto call Add and Done.
|
||||
func (wg *WaitGroup) Go(fn func()) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
fn()
|
||||
}()
|
||||
}
|
||||
|
||||
// ContextValue create a new context with given value
|
||||
func ContextValue(key, value any) context.Context {
|
||||
return context.WithValue(context.Background(), key, value)
|
||||
}
|
||||
|
||||
// SafeMap is a goroutine-safe map.
|
||||
type SafeMap[K comparable, V any] struct {
|
||||
mu sync.RWMutex
|
||||
data map[K]V
|
||||
}
|
||||
|
||||
// NewSafeMap create a new SafeMap instance.
|
||||
func NewSafeMap[K comparable, V any]() *SafeMap[K, V] {
|
||||
return &SafeMap[K, V]{
|
||||
data: make(map[K]V),
|
||||
}
|
||||
}
|
||||
|
||||
// Set value to map.
|
||||
func (m *SafeMap[K, V]) Set(key K, value V) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.data[key] = value
|
||||
}
|
||||
|
||||
// Get value from map.
|
||||
func (m *SafeMap[K, V]) Get(key K) (value V, ok bool) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
value, ok = m.data[key]
|
||||
return value, ok
|
||||
}
|
||||
|
||||
// Delete value from map.
|
||||
func (m *SafeMap[K, V]) Delete(key K) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.data, key)
|
||||
}
|
||||
|
||||
// Range iterate map values.
|
||||
func (m *SafeMap[K, V]) Range(fn func(key K, value V)) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
for key, value := range m.data {
|
||||
fn(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
// Clear do clear all map values.
|
||||
func (m *SafeMap[K, V]) Clear() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.data = make(map[K]V)
|
||||
}
|
||||
|
||||
// Len get map length.
|
||||
func (m *SafeMap[K, V]) Len() int {
|
||||
return len(m.data)
|
||||
}
|
||||
Reference in New Issue
Block a user