Handling response from a go routine
sai teja
Posted on January 5, 2023
There are several use cases of Go Routines and one of the use case is firing multiple routines and capture the response.
Example use cases:-
- Calling multiple Apis and log/use the response.
- Inserting rows into a Table and log the errors if any.
package main
import (
"fmt"
"sync"
)
type Resp struct {
Msg string
}
func main(){
// unbuffered channel to capture response from the go routine
ch:=make(chan Resp)
// sync.WaitGroup type for handling go routines
var wg sync.WaitGroup
for i:=1;i<=5;i++{
// tell WaitGroup to that you are going totrigger a go routine
wg.Add(1)
// trigger
go routine(&wg,i,ch)
}
// fire a go routine to run as demon and give a way to read the response
// and it will wait until all go routines executed successfully
go func(){
// wait until all goroutines are executed successfully
wg.Wait()
// we have to close the channel else below for loop will wait for data to write but data won't come
// this will lead to a deadlock (infinite wait)
close(ch)
}()
// read from response channel
for v:=range ch{
fmt.Println(v.Msg)
}
fmt.Println("signing off ...!!!")
}
func routine(wg *sync.WaitGroup,i int,ch chan Resp){
// tell waitGroup that you are done with this task
defer wg.Done()
//send data to response channel
ch<-Resp{
Msg: fmt.Sprintf("completed task %d..!!",i),
}
}
output:-
completed task 4..!!
completed task 3..!!
completed task 5..!!
completed task 1..!!
completed task 2..!!
signing off ...!!!
please follow medium for interesting things
💖 💪 🙅 🚩
sai teja
Posted on January 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.