我正在實(shí)施一個可以從渠道獲取工作的工作人員池。一直超時后,我發(fā)現(xiàn)當(dāng)一個worker fcn內(nèi)部發(fā)生panic時,即使我做了恢復(fù)機(jī)制,worker還是不會再回到pool中。在 golang 操場上,我能夠重現(xiàn)這個問題:修改后的游樂場代碼:package mainimport "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 時實(shí)施了恐慌。運(yùn)行時,函數(shù)會按預(yù)期發(fā)生恐慌,并按預(yù)期進(jìn)入恢復(fù)狀態(tài)(也不會將值推送到通道中),但是 worker 1 似乎永遠(yuǎn)不會回來。沒有恐慌的輸出:worker 3 started job 1worker 1 started job 2worker 2 started job 3worker 1 finished job 2worker 1 started job 4worker 3 finished job 1worker 3 started job 5worker 2 finished job 3worker 2 started job 6worker 3 finished job 5worker 3 started job 7worker 1 finished job 4worker 1 started job 8worker 2 finished job 6worker 2 started job 9worker 1 finished job 8worker 1 started job 10worker 3 finished job 7worker 2 finished job 9worker 1 finished job 10恐慌輸出:worker 3 started job 12009/11/10 23:00:00 RECOVERY Failed worker: 1worker 2 started job 3worker 2 finished job 3worker 2 started job 4worker 3 finished job 1worker 3 started job 5worker 3 finished job 5worker 3 started job 6worker 2 finished job 4worker 2 started job 7worker 2 finished job 7worker 2 started job 8worker 3 finished job 6worker 3 started job 9worker 3 finished job 9worker 3 started job 10worker 2 finished job 8worker 3 finished job 10恢復(fù)后(或在恢復(fù)過程中)如何將工作人員 1 返回池中
1 回答

翻翻過去那場雪
TA貢獻(xiàn)2065條經(jīng)驗 獲得超14個贊
如果你關(guān)心這些錯誤,你可以將一個errors
通道傳遞給輔助函數(shù),如果他們遇到一個error
,將它發(fā)送到通道然后continue
。主循環(huán)可以處理這些錯誤。
或者,如果您不關(guān)心錯誤,只需continue
跳過該作業(yè)即可。
該continue
語句基本上停止處理循環(huán)的迭代,并繼續(xù)下一個。
- 1 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報
0/150
提交
取消