WaitGroup - Golang tutorial

https://tutorialedge.net/golang/go-waitgroup-tutorial/

When you have a long time job to run in your program

But you need to wait for the result to printout it

--> the best way is to use Waitgroup

package main

import (
"fmt"
"sync"
)

func myFunc(waitgroup *sync.WaitGroup) {
fmt.Println("Inside my goroutine")
waitgroup.Done()
}

func main() {
fmt.Println("Hello World")

var waitgroup sync.WaitGroup
waitgroup.Add(1)
go myFunc(&waitgroup)
waitgroup.Wait()

fmt.Println("Finished Execution")
}


You can use anonymous function

package main

import (
"fmt"
"sync"
)

func main() {
fmt.Println("Hello World")

var waitgroup sync.WaitGroup
waitgroup.Add(1)
go func() {
fmt.Println("Inside my goroutine")
waitgroup.Done()
}()
waitgroup.Wait()

fmt.Println("Finished Execution")
}



If your anonymous function need param input

go func(url string) {
  fmt.Println(url)
}(url)





Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch