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
Post a Comment