1 回答

TA贡献2012条经验 获得超12个赞
您在切片上存在数据竞争queue。并发 goroutines,当通过sync.Mutex锁以受控方式从队列头部弹出元素时。或者使用一个通道来管理工作项的“队列”。
要将您所拥有的转换为使用通道,请更新工作人员以将输入通道作为您的队列 - 并在通道上进行范围,以便每个工作人员可以处理多个任务:
func consumer_task(task_num int, ch <-chan string) {
fmt.Printf("I'm consumer task #%v\n", task_num)
for item := range ch {
fmt.Printf("task %d consuming: Line item: %v\n", task_num, item)
}
// each worker will drop out of their loop when channel is closed
}
从切片更改queue为频道和 feed 项目,如下所示:
queue := make(chan string)
go func() {
// Loop through each line in the file and append it to the queue
for scanner.Scan() {
queue <- scanner.Text()
}
close(queue) // signal to workers that there is no more items
}()
然后只需更新您的工作调度程序代码以添加频道输入:
go func(i int) {
consumer_task(i, queue) // add the queue parameter
wg.Done()
}(i)
https://go.dev/play/p/AzHyztipUZI
- 1 回答
- 0 关注
- 79 浏览
添加回答
举报