Go routine and how to wait for the task done

it is simple

wg := new(sync.WaitGroup)


go func() {
   for i:=0;i<10 ;i++  {
      fmt.Println("Hello %d",i)
      time.Sleep(time.Second/2)
   }
   wg.Done()
}()
wg.Add(1)

go func() {
   for i:=0;i<10 ;i++  {
      fmt.Println("Goodbye %d",i)
      time.Sleep(time.Second)
   }
   wg.Done()
}()
wg.Add(1)

wg.Wait()


Step 1: declare a wait group

Step 2: at the end of task will will call wg.Done() to notify the task done

Step 3: Specify exactly number of the task which need to wait for done by call wg.Add()
If we have 3 task --> call wg.Add(3)
or call 3 times wg.Add(1)

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