如何在Go中将工作人员返回工作池

时间:2019-03-11 16:29:26

标签: multithreading go

我正在实现一个工人池,该工人池可以从某个渠道接管工作。保持超时后,我意识到,即使在我执行恢复机制的情况下,在工作程序fcn内发生紧急情况时,该工作程序仍然不会再次返回到池中。

在golang游乐场,我能够重现该问题:

Worker Pool Reference

修改后的游戏代码:

package main

import "fmt"
import "time"
import "log"

func recovery(id int, results chan<- int) {
    if r := recover(); r != nil {
        log.Print("IN RECOVERY FUNC - Failed worker: ",id)  
        results <- 0
    }
}

func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
    defer recovery(id, results)
    if id == 1 {
        panic("TEST")
    }
        fmt.Println("worker", id, "started job", j)
        time.Sleep(time.Second)
        fmt.Println("worker", id, "finished job", j)
        results <- j * 2
    }
}

func main() {
    jobs := make(chan int, 100)
    results := make(chan int, 100)
    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }
    for j := 1; j <= 10; j++ {
        jobs <- j
    }
    close(jobs)
    for a := 1; a <= 10; a++ {
        <-results
    }
}

为了进行测试,当使用worker 1时,我已经出现了紧急情况。运行时,功能将按预期运行,并且按预期进入恢复状态(也不会将值推入通道),但是工作进程1似乎永远不会返回。

没有恐慌的输出:

worker 3 started job 1
worker 1 started job 2
worker 2 started job 3
worker 1 finished job 2
worker 1 started job 4
worker 3 finished job 1
worker 3 started job 5
worker 2 finished job 3
worker 2 started job 6
worker 3 finished job 5
worker 3 started job 7
worker 1 finished job 4
worker 1 started job 8
worker 2 finished job 6
worker 2 started job 9
worker 1 finished job 8
worker 1 started job 10
worker 3 finished job 7
worker 2 finished job 9
worker 1 finished job 10

出现恐慌的输出:

worker 3 started job 1
2009/11/10 23:00:00 RECOVERY Failed worker: 1
worker 2 started job 3
worker 2 finished job 3
worker 2 started job 4
worker 3 finished job 1
worker 3 started job 5
worker 3 finished job 5
worker 3 started job 6
worker 2 finished job 4
worker 2 started job 7
worker 2 finished job 7
worker 2 started job 8
worker 3 finished job 6
worker 3 started job 9
worker 3 finished job 9
worker 3 started job 10
worker 2 finished job 8
worker 3 finished job 10

如何在恢复后(或在恢复过程中)将工作线程1返回到池中

1 个答案:

答案 0 :(得分:2)

如果您关心这些错误,则可以将一个errors通道传递给工作函数,如果它们遇到一个error,则将其发送到该通道,然后再发送给continue。主循环可以处理这些错误。

或者,如果您不关心该错误,只需continue即可跳过该工作。

continue语句基本上停止处理循环的迭代,并继续执行