我下面代码中的writeWg有死锁问题,帮忙在不影响功能的情况下解决一下 package main import ( "context" "errors" "fmt"…
- User
我下面代码中的writeWg有死锁问题,帮忙在不影响功能的情况下解决一下 package main
import ( "context" "errors" "fmt" "sync" "time"
code"github.com/xuri/excelize/v2")
// Task 定义任务的数据结构 type Task struct { ID int // 批次任务ID BatchRowIndex int // 批次内的行索引 GlobalRowIndex int // 全局行索引(0-9999) Data map[string]interface{} // 输入数据 Result map[string]interface{} // 处理结果 Retries int // 重试次数 }
// TaskFunc 定义任务处理函数类型,返回单个结果 type TaskFunc func(ctx context.Context, data interface{}) (interface{}, error)
// Layer 定义流水线的每一层 type Layer struct { workerCount int timeout time.Duration maxRetries int taskFunc TaskFunc }
// Pipeline 定义整个流水线结构 type Pipeline struct { layers []*Layer }
// NewPipeline 创建一个新的流水线实例 func NewPipeline() *Pipeline { return &Pipeline{ layers: make([]*Layer, 0), } }
// AddLayer 向流水线中添加一层 func (p *Pipeline) AddLayer(taskFunc TaskFunc, workerCount int, timeout time.Duration, maxRetries int) { layer := &Layer{ workerCount: workerCount, timeout: timeout, maxRetries: maxRetries, taskFunc: taskFunc, } p.layers = append(p.layers, layer) }
// Run 启动流水线处理任务,并在每个任务完成时调用回调函数 func (p *Pipeline) Run(input []interface{}, callback func(task *Task)) error { if len(p.layers) == 0 { return errors.New("pipeline has no layers") }
code - Assistant
你在代码中遇到的死锁问题是因为
writeWg.Done()没有被调用足够的次数,导致writeWg.Wait()永远等待下去。具体来说,在pipeline.Run函数的最后一层中,对于task.Result == nil的任务,没有调用writer(task),因此这些任务对应的 没有被调用。