• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Idiomatic goroutine concurrency and error handling

Resolved: Idiomatic goroutine concurrency and error handling

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

In the below code block I am trying to run several routines and get results (Whether success or error) for all of them.
I was wondering if there is a more idiomatic way to achieve this. I went through the errgroup package: https://pkg.go.dev/golang.org/x/sync/errgroup but wasn’t able to find something that may help me here. Any suggestions are welcome.

Answer:

Waitgroup is redundant in this code. Execution is perfectly synced with the loop that is waiting for the channel’s result. Code is not moved forward until all functions finish their work and posted results are read from the channels. Waitgroup is only necessary if your function needs to do any work AFTER results are posted to channels.
I also prefer a slightly different implementation. In a posted implementation, we are not sending both results and errors into the channels every time when the function is executed. Instead, we can send only the result for successful execution and send only an error when the code fails.
The advantage is simplified results/errors processing. We are getting slices of results and errors without nils.
In this example, the function returns a number, and we send its default value of 0 in case of error. It could be complicated to filter out not successful execution results from successful if zero could be legit function execution result.
Same with errors. To check if we have any errors, we can use simple code like if len(errs) != 0.
If you can use external packages, we can get benefits from some multierr package. For example, github.com/hashicorp/go-multierror.

If you have better answer, please add a comment about this, thank you!

go goroutine
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to separate multiple answers in one column, for multiple columns, by creating extra columns

26/03/2023

Resolved: How to set consistent decimal separators in R data frame?

26/03/2023

Resolved: How to resolve LNK2001 in c++ projects

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.