I wrote a library that encapsulates the concurrency logic https://github.com/shomali11/parallelizer , which you can also pass a timeout.
Here is an example without a timeout:
func main() { group := parallelizer.DefaultGroup() group.Add(func() { for char := 'a'; char < 'a'+3; char++ { fmt.Printf("%c ", char) } }) group.Add(func() { for number := 1; number < 4; number++ { fmt.Printf("%d ", number) } }) err := group.Run() fmt.Println() fmt.Println("Done") fmt.Printf("Error: %v", err) }
Output:
a 1 b 2 c 3 Done Error: <nil>
Here is a timeout example:
func main() { options := ¶llelizer.Options{Timeout: time.Second} group := parallelizer.NewGroup(options) group.Add(func() { time.Sleep(time.Minute) for char := 'a'; char < 'a'+3; char++ { fmt.Printf("%c ", char) } }) group.Add(func() { time.Sleep(time.Minute) for number := 1; number < 4; number++ { fmt.Printf("%d ", number) } }) err := group.Run() fmt.Println() fmt.Println("Done") fmt.Printf("Error: %v", err) }
Output:
Done Error: timeout
Raed shomali
source share