我有一个可以并行处理的任务流。但是,具有相同标记的任务必须以FIFO顺序处理。
type task struct {
tag string
data []int
}
func process (ch chan task) {
for t := range ch {
go processTask (t)
}
}
字符串
我需要添加逻辑来防止并行处理具有相同标记的任务。这些任务必须以FIFO顺序处理。
在99%的情况下,标签是唯一的。在极少数情况下,几个任务可能具有相同的标签。如果我们已经处理了一个标签为X
的任务,并且出现了一个标签为X
的新任务,我们必须等到处理完前一个任务,然后再开始下一个任务。
如果有多个带有标签X
的任务正在等待,则必须按照发送到通道的相同顺序处理这些任务。
不应阻止处理带有其他标记的任务。
推荐的方法是什么?
1条答案
按热度按时间wsewodh21#
如果你想只在进程中按标签执行FIFO队列,你可以为每个标签分配一个通道和一个工作器。你可以在Map中跟踪每个标签的通道。
这里有一个实现(https://go.dev/play/p/8r8-oaRaY2x),它非常适合你,你的实际通道消息可以包括一个结果通道。
个字符