Handling response from a go routine

saiteja

sai teja

Posted on January 5, 2023

Handling response from a go routine

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:-

  1. Calling multiple Apis and log/use the response.
  2. 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 ...!!!

Enter fullscreen mode Exit fullscreen mode

please follow medium for interesting things

Sai Teja – Medium

Read writing from Sai Teja on Medium. Software Engineer | Fitness trainer | Random Thinker | https://www.linkedin.com/in/saitejamesala/. Every day, Sai Teja and thousands of other voices read, write, and share important stories on Medium.

favicon medium.com
💖 💪 🙅 🚩
saiteja
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.

Related