1.起固定個數的goroutine
package utils
import (
"sync"
)
type pool struct {
queue chan int
wg *sync.WaitGroup
}
func New(size int) *pool {
if size <= 0 {
size = 1
}
return &pool{
queue: make(chan int, size),
wg: &sync.WaitGroup{},
}
}
func (p *pool) Add(delta int) {
for i := 0; i < delta; i++ {
p.queue <- 1
}
for i := 0; i > delta; i-- {
<-p.queue
}
p.wg.Add(delta)
}
func (p *pool) Done() {
<-p.queue
p.wg.Done()
}
func (p *pool) Wait() {
p.wg.Wait()
}
** // 使用示例**
// 初始化数据,创建10个goroutine
pool := utils.New(10)
for i:=0; i< 100;i++ {
pool.Add(1)
go func() {
DOSomething()
pool.Done()
}
}
pool.Wait()
2.重试机制
func Retry(attempts int, sleep time.Duration, f func() error) (err error) {
for i := 0; ; i++ {
err = f()
if err == nil {
return
}
if i >= (attempts - 1) {
break
}
time.Sleep(sleep)
}
return fmt.Errorf("after %d attempts, last error: %v", attempts, err)
}