package util

import ( 'context' 'errors' 'fmt' 'sync' 'time' )

// GoAndWait 并发处理任务(可控制worker数量) func GoAndWait(workerNum int, tasks ...func() error) (err error) { if workerNum < 1 { workerNum = 1 } lens := len(tasks) if workerNum > lens { workerNum = lens } var wg sync.WaitGroup var once sync.Once ch := make(chan func() error, workerNum) for i := 1; i <= workerNum; i++ { wg.Add(1) go func() { defer func() { wg.Done() if r := recover(); r != nil { once.Do(func() { err = errors.New(fmt.Sprintf('%v', r)) }) } }() for task := range ch { if e := task(); e != nil { once.Do(func() { err = e }) } } }() } for _, task := range tasks { ch <- task } close(ch) wg.Wait() return }

// Sleep 睡眠 (含Context Close处理) func Sleep(ctx context.Context, d time.Duration) bool { timer := time.NewTimer(d) select { case <-ctx.Done(): return false case <-timer.C: return true } }

// 代码优化建议:

  1. 函数名 GoAndWait 不太符合 Go 语言的命名规范,应该改为 goAndWait 或者 GoAndWait
  2. 在处理任务的 goroutine 中,如果一个任务执行失败,会导致 err 被赋值为该错误,并使所有正在执行的任务都立即停止。这可能不是期望的行为,需要根据具体需求进行调整。
  3. 函数 Sleep 的返回值为 bool 类型,建议改为 error 类型,以便在出错时返回具体的错误信息。
GoLang 并发处理任务代码优化建议

原文地址: https://www.cveoy.top/t/topic/oBIc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录