I have the following code example. I want to support 4 goroutines all the time. They have the opportunity to panic. In case of panic, I have a recovery where I restart goroutine.
The way I implemented the work, but I'm not sure if he did it right. Any thoughts
package main import ( "fmt" "time" ) var gVar string var pCount int func pinger(c chan int) { for i := 0; ; i++ { fmt.Println("adding ", i) c <- i } } func printer(id int, c chan int) { defer func() { if err := recover(); err != nil { fmt.Println("HERE", id) fmt.Println(err) pCount++ if pCount == 5 { panic("TOO MANY PANICS") } else { go printer(id, c) } } }() for { msg := <-c fmt.Println(id, "- ping", msg, gVar) if msg%5 == 0 { panic("PANIC") } time.Sleep(time.Second * 1) } } func main() { var c chan int = make(chan int, 2) gVar = "Preflight" pCount = 0 go pinger(c) go printer(1, c) go printer(2, c) go printer(3, c) go printer(4, c) var input string fmt.Scanln(&input) }
source share