我正在编写一个应用程序,用户可以从多个“作业”(实际上是 URL)开始。在开始(主程序)时,我将这些 URL 添加到队列中,然后启动 x 处理这些 URL 的 goroutine。
在特殊情况下,URL 指向的资源可能包含更多必须添加到队列中的 URL。这 3 名工人正在等待新的工作进入并处理它们。问题是:一旦每个工人都在等待工作(并且没有人生产任何工作),工人就应该完全停止。所以要么所有这些都有效,要么没有一个有效。
我当前的实现看起来像这样,我认为它不优雅。不幸的是,我想不出一个更好的方法来不包含竞争条件,而且我不完全确定这个实现是否真的按预期工作:
var queue // from somewhere
const WORKER_COUNT = 3
var done chan struct{}
func work(working chan int) {
absent := make(chan struct{}, 1)
// if x>1 jobs in sequence are popped, send to "absent" channel only 1 struct.
// This implementation also assumes that the select statement will be evaluated "in-order" (channel 2 only if channel 1 yields nothing) - is this actually correct? EDIT: It is, according to the specs.
one := false
for {
select {
case u, ok := <-queue.Pop():
if !ok {
close(absent)
return
}
if !one {
// I have started working (delta + 1)
working <- 1
absent <- struct{}{}
one = true
}
// do work with u (which may lead to queue.Push(urls...))
case <-absent: // no jobs at the moment. consume absent => wait
one = false
working <- -1
}
}
}
func Start() {
working := make(chan int)
for i := 0; i < WORKER_COUNT; i++ {
go work(working)
}
// the amount of actually working workers...
sum := 0
for {
delta := <-working
sum += delta
if sum == 0 {
queue.Close() // close channel -> kill workers.
done <- struct{}{}
return
}
}
}
有没有更好的方法来解决这个问题?
德玛西亚99
相关分类