Difference between plain go func and for loop in go func

Issue

I have some question regarding difference between plain go func and for loop in go func:

  1. Plain go Func:

    func asyncTask(){
        //...something
    }
    

    in order to trigger asyncTask, we can simply:

    func main(){
        go asyncTask()
    }
    
  2. make a for loop to monitor channel:

    func (c *Container) asyncTask(){
        go func(){
            for {
                select {
                    case <- c.someChan:
                        //...do something
                    case <-c.ctx.Done():
                        //...prevent leaking
                }
            }
        }()
    }
    

    to trigger:

    func (c *Container) trigger(){
        c.someChan <- val
    }
    

My questions are:

  1. I understand second scenario most fit the case when we wish to manage async task in a queue.
    But speaking for performance out of frequently triggered async task (which cannot be block), which method is better?

  2. Is there any best practice in general to handle async task in GoLang?

Solution

You can use model #1 with WaitGroups when you have goroutines for which you need to account for and are bothered only about their exit and as such otherwise don’t need to manage etc.

You can use model #2 when you need explicit management / control / communication. Channel communication is NOT free – sending and receiving routines need synchronization/channels need locking when values are sent, lot of things will have to happen under the hood.

Unless the need be, definitely option #1 is the way to go. See what’s the simplest possible solution for your problem – I know it’s easy to preach, but simplicity may take some time to come by.

Answered By – Ravi R

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.