Golang : Wait and sync.WaitGroup example
There are time when we need to get multiple things done concurrently first and make sure the processes result are synchronized before moving on to the next process. This can be done with the Sync package http://golang.org/pkg/sync/ in Golang.
For example, a template HTML page must wait for the database queries to be completed before being rendered to PDF and write to http.ResponseWriter.
This example below will simulate a waitgroup with some time delay. You can modify it to implement your own waitgroup for your code.
package main
import (
"fmt"
"sync"
"time"
)
func f(w *sync.WaitGroup, sec int) {
fmt.Println("Time : ", time.Now())
time.Sleep(time.Duration(sec) * time.Second)
fmt.Println("Time : ", time.Now())
w.Done()
fmt.Println("Wait completed")
}
func main() {
// send query to database and wait
fmt.Println("Starting to wait")
var wg sync.WaitGroup
wg.Add(2) // for example, wait for 2 concurrent queries before this wait group is done
go func(swg *sync.WaitGroup, sec int) {
fmt.Println("Time : ", time.Now())
<-time.After(time.Duration(sec) * time.Millisecond)
swg.Done()
}(&wg, 2500)
go f(&wg, 4) // simulate a concurrent wait 4 second
wg.Wait()
fmt.Println("Finished")
}
References :
See also : Golang : Concurrency and goroutine example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+16.7k Golang : Get command line arguments
+10.5k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+7.9k Golang : How to extract video or image files from html source code
+28k Golang : Get time.Duration in year, month, week or day
+15.5k Golang : How to generate QR codes?
+4.6k Golang : What is StructTag and how to get StructTag's value?
+10.8k Golang : Convert a rune to unicode style string \u
+21.4k Golang : simulate tail -f or read last line from log file example
+11.3k Golang : How to display image file or expose CSS, JS files from localhost?
+12.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+11.5k Golang : Get terminal width and height example
+21.7k Golang : Randomly pick an item from a slice/array example