Wait For All Goroutines to Finish Using WaitGroup in Golang

PROGRAM:

package main

import (
"fmt"
"sync"
"time"
)

func conFun(wg *sync.WaitGroup, count int) {
time.Sleep(time.Duration(count) * time.Second)
fmt.Println(time.Now(), "Go routine -", count, "finished")
wg.Done()
}

func main() {
var wg sync.WaitGroup

/* initialize wait group counter to 5 */
wg.Add(5)

count := 5
for it := 1; it <= 5; it++ {
go conFun(&wg, it)
}

fmt.Println(time.Now(), "Waiting for", count, "go routines to finish")
wg.Wait()
fmt.Println(time.Now(), "All", count, "go routines were finished")
}


OUTPUT:

sujin@sujin:~$ go build waitgroup.go 

sujin@sujin:~$ ./waitgroup 
2015-06-14 18:09:13.566058414 +0530 IST Waiting for 5 go routines to finish
2015-06-14 18:09:14.566488928 +0530 IST Go routine - 1 finished
2015-06-14 18:09:15.566480056 +0530 IST Go routine - 2 finished
2015-06-14 18:09:16.566474898 +0530 IST Go routine - 3 finished
2015-06-14 18:09:17.566485676 +0530 IST Go routine - 4 finished
2015-06-14 18:09:18.566478132 +0530 IST Go routine - 5 finished
2015-06-14 18:09:18.566549988 +0530 IST All 5 go routines were finished

No comments:

Post a Comment